robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
34.3 KiB1116 linesraw
1--- @brief
2--- [vim.fs.copy()]()
3---
4--- Use |filecopy()| or |uv.fs_copyfile()| to performantly copy an existing file.
5---
6--- Example:
7---
8--- ```lua
9--- vim.fn.filecopy('foo.txt', 'bar.txt')
10--- ```
11---
12--- [vim.fs.exists()]()
13---
14--- Use |uv.fs_stat()| to check a file's type, and whether it exists.
15---
16--- Example:
17---
18--- ```lua
19--- if vim.uv.fs_stat(file) then
20---   vim.print('file exists')
21--- end
22--- ```
23---
24--- [vim.fs.read()]()
25---
26--- You can use |readblob()| to get a file's contents without explicitly opening/closing it.
27--- Or use |io.lines()| to iterate lines in a text file.
28---
29--- Example:
30--- ```lua
31--- vim.print(vim.fn.readblob('.git/config'))
32--- ```
33---
34--- [vim.fs.write()]()
35---
36--- You can use |writefile()| to write a file without explicitly opening/closing it.
37---
38--- Example:
39--- ```lua
40--- vim.fn.writefile('foo\0bar', 'data.bin', 'b')
41--- ```
42
43local uv = vim.uv
44
45local M = {}
46
47local os_sep = package.config:sub(1, 1)
48local iswin = os_sep == '\\'
49
50--- Iterate over all the parents of the given path (not expanded/resolved, the caller must do that).
51---
52--- Example:
53---
54--- ```lua
55--- local root_dir
56--- for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
57---   if vim.fn.isdirectory(dir .. '/.git') == 1 then
58---     root_dir = dir
59---     break
60---   end
61--- end
62---
63--- if root_dir then
64---   print('Found git repository at', root_dir)
65--- end
66--- ```
67---
68---@since 10
69---@param start (string) Initial path.
70---@return fun(_, dir: string): string? # Iterator
71---@return nil
72---@return string|nil
73function M.parents(start)
74  return function(_, dir)
75    local parent = M.dirname(dir)
76    if parent == dir then
77      return nil
78    end
79
80    return parent
81  end,
82    nil,
83    start
84end
85
86--- Gets the parent directory of the given path (not expanded/resolved, the caller must do that).
87---
88---@since 10
89---@generic T : string|nil
90---@param file T Path
91---@return T # Parent directory of `file`
92function M.dirname(file)
93  if file == nil then
94    return nil
95  end
96  vim.validate('file', file, 'string')
97  --- @cast file string
98  local dir = vim.fn.fnamemodify(file, ':h')
99  if iswin then
100    return (dir:gsub(os_sep, '/'))
101  end
102  return dir
103end
104
105--- Gets the basename of the given path (not expanded/resolved).
106---
107---@since 10
108---@generic T : string|nil
109---@param file T Path
110---@return T # Basename of `file`
111function M.basename(file)
112  if file == nil then
113    return nil
114  end
115  vim.validate('file', file, 'string')
116  --- @cast file string
117  local name = vim.fn.fnamemodify(file, ':t')
118  if iswin then
119    return (name:gsub(os_sep, '/'))
120  end
121  return name
122end
123
124--- Concatenates partial paths (one absolute or relative path followed by zero or more relative
125--- paths). Slashes are normalized: redundant slashes are removed, and (on Windows) backslashes are
126--- replaced with forward-slashes. Empty segments are removed. Paths are not expanded/resolved.
127---
128--- Examples:
129--- - "foo/", "/bar" => "foo/bar"
130--- - "", "after/plugin" => "after/plugin"
131--- - Windows: "a\foo\", "\bar" => "a/foo/bar"
132---
133---@since 12
134---@param ... string
135---@return string
136function M.joinpath(...)
137  local n = select('#', ...)
138  ---@type string[]
139  local segments = {}
140  for i = 1, n do
141    local s = select(i, ...)
142    if s and #s > 0 then
143      segments[#segments + 1] = s
144    end
145  end
146
147  local path = table.concat(segments, '/')
148
149  return (path:gsub(iswin and '[/\\][/\\]*' or '//+', '/'))
150end
151
152--- Gets a filesystem-safe, mnemonic slug (readable prefix + short hash) of an arbitrary filepath or
153--- other "identity string".
154---
155--- - The input is normalized so equivalent paths produce the same result.
156--- - A hash of the normalized input is appended to prevent collisions.
157--- - Unsafe chars are replaced with "-".
158--- - `$HOME` is replaced with "~".
159--- - URIs (`scheme://...`) are prefixed with "=uri-{scheme}-".
160--- - UNC paths (Windows) are prefixed with "=unc-".
161--- - If `opts.maxlen` is exceeded, the result will be truncated to `{head}~~~{tail}-{hash8}`.
162--- - If the sanitized name is empty, the reserved label `=special` will be used.
163---
164--- Examples:
165---
166--- ```lua
167--- vim.print(vim.fs.slug('/tmp/test/foo.md'))           --> "tmp-test-foo.md-{hash}"
168--- vim.print(vim.fs.slug('C:/src/project/main.c'))      --> "C--src-project-main.c-{hash}"
169--- vim.print(vim.fs.slug(vim.fn.expand('~/file.txt')))  --> "~-file.txt-{hash}"
170--- vim.print(vim.fs.slug('---'))                        --> "=special-{hash}"
171--- vim.print(vim.fs.slug('term://foo/bar//123:bash'))   --> "=uri-term-foo-bar-123-bash-{hash}"
172--- vim.print(vim.fs.slug(('/a/very/long/path'):rep(10) .. '/file.txt', { maxlen = 60 }))
173---    --> "a-very-long-~~~-path-a-very-long-path-file.txt-{hash}"
174--- ```
175---
176---@since 15
177---@param path string Filepath (or other identity string).
178---@param opts? { maxlen?: integer } #
179---  - maxlen: (integer, default: 180) Max length (bytes) of the result.
180---@return string # Filesystem-safe, mnemonic slug.
181function M.slug(path, opts)
182  vim.validate('path', path, 'string')
183  opts = opts or {}
184  vim.validate('maxlen', opts.maxlen, function(v)
185    return type(v) == 'number' and v >= 8
186  end, true, '`opts.maxlen` must be >= 8')
187  local maxlen = opts.maxlen or 180
188
189  -- Capture URI scheme before normalize() collapses "://" to ":/" (which looks like "C:/")
190  local uri_scheme = path:match('^([a-zA-Z][a-zA-Z0-9.+-]*)://') ---@type string?
191
192  -- Normalize before computing the hash so equivalent paths produce the same result
193  path = vim.fs.normalize(path, { plain = true })
194  local s = path
195
196  if uri_scheme then
197    -- Replace scheme prefix with "=uri-{scheme}-"
198    s = '=uri-' .. uri_scheme .. '-' .. s:sub(#uri_scheme + 3) -- `+ 3` skips`:/`
199  elseif vim.startswith(s, '/') or (iswin and s:match('^%w:/')) then
200    -- Replace $HOME with `~`
201    -- `fnamemodify` resolves relative paths against CWD, so only call it on absolute paths
202    s = vim.fn.fnamemodify(s, ':~')
203  end
204
205  -- Replace UNC `//...` (Windows only) with `=unc-`
206  -- `//?/` and `//./` are NT namespace prefixes, not UNC
207  if
208    iswin
209    and vim.startswith(s, '//')
210    and not vim.startswith(s, '//?/')
211    and not vim.startswith(s, '//./')
212  then
213    s = '=unc-' .. s:sub(3)
214  end
215
216  -- Sanitize unsafe chars and trim trailing "-" and "."
217  s = s:gsub('[%c%s/\\:*?"<>|]', '-')
218  s = s:gsub('[.-]+$', '')
219  -- Strip the leading "-" from an absolute path
220  s = s:gsub('^-', '')
221
222  -- Always compute the hash to prevent collisions
223  local hash8 = vim.fn.sha256(path):sub(1, 8)
224
225  -- Fully scrubbed path uses the reserved prefix
226  if s == '' then
227    s = '=special'
228  end
229
230  -- Within maxlen: "{name}-{hash8}"
231  if #s + 1 + #hash8 <= maxlen then
232    return s .. '-' .. hash8
233  end
234
235  -- "{head}~~~{tail}-{hash8}"
236  local budget = maxlen - 12 -- 3 for "~~~", 1 for "-", 8 for hash
237  if budget < 1 then
238    -- No room for a readable form: degrade to a plain hash (maxlen >= 8 == #hash8).
239    return hash8
240  end
241  local head_len = math.floor(budget / 3)
242  local h = (
243    s:sub(1, head_len):match('^.*()-') --[[@as integer?]]
244  ) or head_len -- byte position where {head} ends
245  if h == head_len and h >= 1 then
246    -- No "-" found in prefix: ensure we don't split a UTF-8 character.
247    -- `vim.str_utf_start` returns an offset (<= 0) from the byte position to the character start.
248    -- `vim.str_utf_end` returns an offset (>= 0) to the character's last byte.
249    local char_start = h + vim.str_utf_start(s, h) ---@type integer
250    if char_start + vim.str_utf_end(s, char_start) > h then
251      h = char_start - 1
252    end
253  end
254  -- Always in [h + 4, #s]: the "{name}-{hash8}" case above handled #s <= budget + 3.
255  local tail_start = #s - budget + h + 1
256  local t = s:find('-', tail_start, true) or tail_start -- byte position where {tail} starts
257  -- If we fall back to a byte position, step forward past a split character
258  if t == tail_start then
259    local offset_start = vim.str_utf_start(s, t)
260    if offset_start < 0 then
261      local char_start = t + offset_start ---@type integer
262      t = char_start + vim.str_utf_end(s, char_start) + 1
263    end
264  end
265  return s:sub(1, h) .. '~~~' .. s:sub(t) .. '-' .. hash8
266end
267
268--- Wrapper around `uv.fs_scandir_next()` that ensures a file type is returned.
269---
270--- @param fs uv.uv_fs_t
271--- @param path string
272--- @return string?
273--- @return string?
274local function fs_scandir_next(fs, path)
275  -- use uv.fs_lstat instead of uv.fs_stat to avoid descending into a symlink entry as a directory/file
276  local name, etype = uv.fs_scandir_next(fs)
277
278  if not name then
279    return
280  end
281
282  if etype == nil then
283    local stat = uv.fs_lstat(M.joinpath(path, name))
284    -- Workaround #39612 https://github.com/luvit/luv/issues/660
285    etype = stat and stat.type or 'unknown'
286  end
287
288  return name, etype
289end
290
291--- @class vim.fs.dir.Opts
292--- @inlinedoc
293---
294--- How deep to traverse.
295--- (default: `1`)
296--- @field depth? integer
297---
298--- Report errors via the iterator's third value ("err"), instead of silently skipping.
299--- (default: `false`)
300--- @field err? boolean
301---
302--- Predicate to control traversal.
303--- Return false to stop searching the current directory.
304--- Only useful when depth > 1
305--- Return an iterator over the items located in {path}
306--- @field skip? (fun(dir_name: string): boolean)
307---
308--- Follow symbolic links.
309--- (default: `false`)
310--- @field follow? boolean
311---
312--- Do not expand special forms like "~" and "$" in {path}.
313--- (default: `false`)
314--- @field plain? boolean
315
316--- Gets an iterator over items found in `path` (normalized via |vim.fs.normalize()|).
317---
318--- Example:
319---
320--- ```lua
321--- for name, type, err in vim.fs.dir(path, { err = true }) do
322---   if err then
323---     -- Failed to scan directory {name} (may be the root {path} itself).
324---   end
325--- end
326--- ```
327---
328---@since 10
329---@param path (string) Directory to iterate over, expanded (unless
330---                     `opts.plain=true`) and normalized.
331---@param opts? vim.fs.dir.Opts
332---@return fun(): string?, string?, string? # Iterator over items in {path}, yielding (name, type, err):
333---        - name: Basename of the item relative to {path}.
334---        - type: One of: "file", "directory", "link", "fifo", "socket", "char", "block", "unknown".
335---        - err: Error string, or nil. Only if `opts.err=true`. If the root {path} itself could not
336---          be scanned, yields a single (name, nil, err) item.
337function M.dir(path, opts)
338  opts = opts or {}
339
340  vim.validate('path', path, 'string')
341  vim.validate('depth', opts.depth, 'number', true)
342  vim.validate('err', opts.err, 'boolean', true)
343  vim.validate('follow', opts.follow, 'boolean', true)
344  vim.validate('skip', opts.skip, 'function', true)
345  vim.validate('plain', opts.plain, 'boolean', true)
346
347  path = M.normalize(path, { plain = opts.plain })
348
349  local rootfs, rooterr = uv.fs_scandir(path)
350
351  if not rootfs then
352    -- Root scan failed:
353    -- - If opts.err=false, behave as an empty listing (back-compat).
354    -- - If opts.err=true, surface yield a single (name, nil, err) result.
355    local done = not opts.err
356    return function()
357      if done then
358        return nil
359      end
360      done = true
361      return path, nil, rooterr
362    end
363  end
364
365  if not opts.depth or opts.depth == 1 then
366    return function()
367      return fs_scandir_next(rootfs, path)
368    end
369  end
370
371  --- @async
372  return coroutine.wrap(function()
373    ---@type [string, integer, uv.uv_fs_t][]
374    local dirs = { { path, 1, rootfs } }
375    while #dirs > 0 do
376      --- @type string, integer, any
377      local dir0, level, fs = unpack(table.remove(dirs, 1))
378      local dir = level == 1 and dir0 or M.joinpath(path, dir0)
379      while fs do
380        local name, t = fs_scandir_next(fs, dir)
381        if not name then
382          break
383        end
384        local f = level == 1 and name or M.joinpath(dir0, name)
385        local err_scan = nil
386        if
387          opts.depth
388          and level < opts.depth
389          and (t == 'directory' or (t == 'link' and opts.follow and (
390            uv.fs_stat(M.joinpath(path, f)) or {}
391          ).type == 'directory'))
392          and (not opts.skip or opts.skip(f) ~= false)
393        then
394          local fs_next, err = uv.fs_scandir(M.joinpath(path, f))
395          if not fs_next then
396            err_scan = opts.err and err or nil
397          else
398            dirs[#dirs + 1] = { f, level + 1, fs_next }
399          end
400        end
401        coroutine.yield(f, t, err_scan)
402      end
403    end
404  end)
405end
406
407--- @class vim.fs.find.Opts
408--- @inlinedoc
409---
410--- Path to begin searching from, defaults to |current-directory|. Not expanded.
411--- @field path? string
412---
413--- Search upward through parent directories. Otherwise, search child directories (recursively).
414--- (default: `false`)
415--- @field upward? boolean
416---
417--- Stop searching when this directory is reached. The directory itself is not searched.
418--- @field stop? string
419---
420--- Find only items of the given type. If omitted, all items that match {names} are included.
421--- @field type? string
422---
423--- Stop searching after this many matches. Use `math.huge` for "unlimited".
424--- (default: `1`)
425--- @field limit? number
426---
427--- Follow symbolic links.
428--- (default: `false`)
429--- @field follow? boolean
430
431--- Find files or directories (or other items as specified by `opts.type`) in the given path.
432---
433--- Finds items given in {names} starting from {path}. If {upward} is "true"
434--- then the search traverses upward through parent directories; otherwise,
435--- the search traverses downward. Note that downward searches are recursive
436--- and may search through many directories! If {stop} is non-nil, then the
437--- search stops when the directory given in {stop} is reached. The search
438--- terminates when {limit} (default 1) matches are found. You can set {type}
439--- to "file", "directory", "link", "socket", "char", "block", or "fifo"
440--- to narrow the search to find only that type.
441---
442--- Examples:
443---
444--- ```lua
445--- -- List all test directories under the runtime directory.
446--- local dirs = vim.fs.find(
447---   { 'test', 'tst', 'testdir' },
448---   { limit = math.huge, type = 'directory', path = './runtime/' }
449--- )
450---
451--- -- Get all "lib/*.cpp" and "lib/*.hpp" files, using Lua patterns.
452--- -- Or use `vim.glob.to_lpeg(…):match(…)` for glob/wildcard matching.
453--- local files = vim.fs.find(function(name, path)
454---   return name:match('.*%.[ch]pp$') and path:match('[/\\]lib$')
455--- end, { limit = math.huge, type = 'file' })
456--- ```
457---
458---@since 10
459---@param names (string|string[]|fun(name: string, path: string): boolean) Names of the items to find.
460---             Must be base names, paths and globs are not supported when {names} is a string or a table.
461---             If {names} is a function, it is called for each traversed item with args:
462---             - name: base name of the current item
463---             - path: full path of the current item
464---
465---             The function should return `true` if the given item is considered a match.
466---
467---@param opts? vim.fs.find.Opts Optional keyword arguments:
468---@return string[] # Normalized paths |vim.fs.normalize()| of all matching items.
469---@return string[] # Errors collected while searching.
470function M.find(names, opts)
471  opts = opts or {}
472  vim.validate('names', names, { 'string', 'table', 'function' })
473  vim.validate('path', opts.path, 'string', true)
474  vim.validate('upward', opts.upward, 'boolean', true)
475  vim.validate('stop', opts.stop, 'string', true)
476  vim.validate('type', opts.type, 'string', true)
477  vim.validate('limit', opts.limit, 'number', true)
478  vim.validate('follow', opts.follow, 'boolean', true)
479
480  if type(names) == 'string' then
481    names = { names }
482  end
483
484  local path = opts.path or assert(uv.cwd())
485  local stop = opts.stop
486  local limit = opts.limit or 1
487
488  local matches = {} --- @type string[]
489  local errors = {} --- @type string[]
490
491  --- @param match string
492  local function add(match)
493    matches[#matches + 1] = M.normalize(match)
494    if #matches == limit then
495      return true
496    end
497  end
498
499  if opts.upward then
500    if path == stop then
501      return matches, errors
502    end
503
504    local test --- @type fun(p: string): string[]
505
506    if type(names) == 'function' then
507      --- @param p string
508      test = function(p)
509        local t = {}
510        for name, type, err in M.dir(p, { err = true }) do
511          if err ~= nil then
512            table.insert(errors, err)
513          elseif (not opts.type or opts.type == type) and names(name, p) then
514            table.insert(t, M.joinpath(p, name))
515          end
516        end
517        return t
518      end
519    else
520      --- @param p string
521      test = function(p)
522        local t = {} --- @type string[]
523        local ok, aerr = uv.fs_access(p, 'R') -- Check if the root dir is readable.
524        if not ok then
525          table.insert(errors, aerr)
526          return t
527        end
528        for _, name in ipairs(names) do
529          local f = M.joinpath(p, name)
530          local stat = uv.fs_stat(f)
531          if stat and (not opts.type or opts.type == stat.type) then
532            t[#t + 1] = f
533          end
534        end
535
536        return t
537      end
538    end
539
540    for _, match in ipairs(test(path)) do
541      if add(match) then
542        return matches, errors
543      end
544    end
545
546    for parent in M.parents(path) do
547      if stop and parent == stop then
548        break
549      end
550
551      for _, match in ipairs(test(parent)) do
552        if add(match) then
553          return matches, errors
554        end
555      end
556    end
557  else
558    local dirs = { path }
559    while #dirs > 0 do
560      local dir = table.remove(dirs, 1)
561      if stop and dir == stop then
562        break
563      end
564
565      for other, type_, err in M.dir(dir, { err = true }) do
566        if err ~= nil then
567          table.insert(errors, err)
568        else
569          -- Keep joinpath() calls inside the match and traversal branches. Joining paths for rejected
570          -- entries can account for up to ~25% of the total search time.
571          if type(names) == 'function' then
572            if (not opts.type or opts.type == type_) and names(other, dir) then
573              if add(M.joinpath(dir, other)) then
574                return matches, errors
575              end
576            end
577          else
578            for _, name in ipairs(names) do
579              if name == other and (not opts.type or opts.type == type_) then
580                if add(M.joinpath(dir, other)) then
581                  return matches, errors
582                end
583              end
584            end
585          end
586
587          if type_ == 'directory' or (type_ == 'link' and opts.follow) then
588            local f = M.joinpath(dir, other)
589            if type_ == 'directory' or (uv.fs_stat(f) or {}).type == 'directory' then
590              dirs[#dirs + 1] = f
591            end
592          end
593        end
594      end
595    end
596  end
597
598  return matches, errors
599end
600
601--- Find the first parent directory containing a specific "marker", relative to a file path or
602--- buffer.
603---
604--- If the buffer is unnamed (has no backing file) or has a non-empty 'buftype' then the search
605--- begins from Nvim's |current-directory|.
606---
607--- Examples:
608---
609--- ```lua
610--- -- Find the root of a Python project, starting from file 'main.py'
611--- vim.fs.root(vim.fs.joinpath(vim.env.PWD, 'main.py'), {'pyproject.toml', 'setup.py' })
612---
613--- -- Find the root of a git repository
614--- vim.fs.root(0, '.git')
615---
616--- -- Find the parent directory containing any file with a .csproj extension
617--- vim.fs.root(0, function(name, path)
618---   return vim.fs.ext(name) == 'csproj'
619--- end)
620---
621--- -- Find the first ancestor directory containing EITHER "stylua.toml" or ".luarc.json"; if
622--- -- not found, find the first ancestor containing ".git":
623--- vim.fs.root(0, { { 'stylua.toml', '.luarc.json' }, '.git' })
624--- ```
625---
626--- @since 12
627--- @param source integer|string Buffer number (0 for current buffer) or file path (absolute or
628---               relative, expanded via `abspath()`) to begin the search from.
629--- @param marker (string|string[]|fun(name: string, path: string): boolean)[]|string|fun(name: string, path: string): boolean
630---               Filename, function, or list thereof, that decides how to find the root. To
631---               indicate "equal priority", specify items in a nested list `{ { 'a.txt', 'b.lua' }, … }`.
632---               A function item must return true if `name` and `path` are a match. Each item
633---               (which may itself be a nested list) is evaluated in-order against all ancestors,
634---               until a match is found.
635--- @return string? # Directory path containing one of the given markers, or nil if no directory was
636---                   found.
637function M.root(source, marker)
638  vim.validate('source', source, { 'number', 'string' })
639  vim.validate('marker', marker, { 'string', 'table', 'function' })
640
641  local path ---@type string
642  if type(source) == 'string' then
643    path = source
644  elseif type(source) == 'number' then
645    if vim.bo[source].buftype ~= '' then
646      path = assert(uv.cwd())
647    else
648      path = vim.api.nvim_buf_get_name(source)
649    end
650  else
651    error('invalid type for argument "source": expected string or buffer number')
652  end
653
654  local markers = type(marker) == 'table' and marker or { marker }
655  for _, mark in ipairs(markers) do
656    local paths = M.find(mark, {
657      upward = true,
658      path = M.abspath(path),
659    })
660
661    if #paths ~= 0 then
662      local dir = M.dirname(paths[1])
663      return dir and M.abspath(dir) or nil
664    end
665  end
666
667  return nil
668end
669
670--- Split a Windows path into a prefix and a body, such that the body can be processed like a POSIX
671--- path. The path must use forward slashes as path separator.
672---
673--- Does not check if the path is a valid Windows path. Invalid paths will give invalid results.
674---
675--- Examples:
676--- - `//./C:/foo/bar` -> `//./C:`, `/foo/bar`
677--- - `//?/UNC/server/share/foo/bar` -> `//?/UNC/server/share`, `/foo/bar`
678--- - `//./system07/C$/foo/bar` -> `//./system07`, `/C$/foo/bar`
679--- - `C:/foo/bar` -> `C:`, `/foo/bar`
680--- - `C:foo/bar` -> `C:`, `foo/bar`
681---
682--- @param path string Path to split.
683--- @return string, string, boolean : prefix, body, whether path is invalid.
684local function split_windows_path(path)
685  local prefix = ''
686
687  --- Match pattern. If there is a match, move the matched pattern from the path to the prefix.
688  --- Returns the matched pattern.
689  ---
690  --- @param pattern string Pattern to match.
691  --- @return string|nil Matched pattern
692  local function match_to_prefix(pattern)
693    local match = path:match(pattern)
694
695    if match then
696      prefix = prefix .. match --[[ @as string ]]
697      path = path:sub(#match + 1)
698    end
699
700    return match
701  end
702
703  local function process_unc_path()
704    return match_to_prefix('[^/]+/+[^/]+/+')
705  end
706
707  if match_to_prefix('^//[?.]/') then
708    -- Device paths
709    local device = match_to_prefix('[^/]+/+')
710
711    -- Return early if device pattern doesn't match, or if device is UNC and it's not a valid path
712    if not device or (device:match('^UNC/+$') and not process_unc_path()) then
713      return prefix, path, false
714    end
715  elseif match_to_prefix('^//') then
716    -- Process UNC path, return early if it's invalid
717    if not process_unc_path() then
718      return prefix, path, false
719    end
720  elseif path:match('^%w:') then
721    -- Drive paths
722    prefix, path = path:sub(1, 2), path:sub(3)
723  end
724
725  -- If there are slashes at the end of the prefix, move them to the start of the body. This is to
726  -- ensure that the body is treated as an absolute path. For paths like C:foo/bar, there are no
727  -- slashes at the end of the prefix, so it will be treated as a relative path, as it should be.
728  local trailing_slash = prefix:match('/+$')
729
730  if trailing_slash then
731    prefix = prefix:sub(1, -1 - #trailing_slash)
732    path = trailing_slash .. path --[[ @as string ]]
733  end
734
735  return prefix, path, true
736end
737
738--- Resolve `.` and `..` components in a POSIX-style path. This also removes extraneous slashes.
739--- `..` is not resolved if the path is relative and resolving it requires the path to be absolute.
740--- If a relative path resolves to the current directory, an empty string is returned.
741---
742--- @see M.normalize()
743--- @param path string Path to resolve.
744--- @return string Resolved path.
745local function path_resolve_dot(path)
746  local is_path_absolute = vim.startswith(path, '/')
747  local new_path_components = {}
748
749  for component in vim.gsplit(path, '/') do
750    if component == '.' or component == '' then -- luacheck: ignore 542
751      -- Skip `.` components and empty components
752    elseif component == '..' then
753      if #new_path_components > 0 and new_path_components[#new_path_components] ~= '..' then
754        -- For `..`, remove the last component if we're still inside the current directory, except
755        -- when the last component is `..` itself
756        table.remove(new_path_components)
757      elseif is_path_absolute then -- luacheck: ignore 542
758        -- Reached the root directory in absolute path, do nothing
759      else
760        -- Reached current directory in relative path, add `..` to the path
761        table.insert(new_path_components, component)
762      end
763    else
764      table.insert(new_path_components, component)
765    end
766  end
767
768  return (is_path_absolute and '/' or '') .. table.concat(new_path_components, '/')
769end
770
771--- Expand tilde (~) character at the beginning of the path to the user's home directory.
772---
773--- @param path string Path to expand.
774--- @param sep string|nil Path separator to use. Uses os_sep by default.
775--- @return string Expanded path.
776local function expand_home(path, sep)
777  sep = sep or os_sep
778
779  if vim.startswith(path, '~') then
780    local home = uv.os_homedir() or '~' --- @type string
781
782    if home:sub(-1) == sep then
783      home = home:sub(1, -2)
784    end
785
786    path = home .. path:sub(2) --- @type string
787  end
788
789  return path
790end
791
792--- @class vim.fs.normalize.Opts
793--- @inlinedoc
794---
795--- Expand environment variables (deprecated).
796--- (default: `true`)
797--- @field package expand_env? boolean
798---
799--- Do not expand environment variables and leading tildes "~".
800--- (default: `false`)
801--- @field plain? boolean
802---
803--- @field package _fast? boolean
804---
805--- Path is a Windows path.
806--- (default: `true` in Windows, `false` otherwise)
807--- @field win? boolean
808
809--- Normalize a path to a standard format. Expands environment variables, and tilde "~" at the
810--- beginning of the path. Resolves "." and ".." components, except when the path is relative and
811--- resolving it would produce an absolute path.
812---
813--- - "." as the only part in a relative path:
814---   - "." => "."
815---   - "././" => "."
816--- - ".." when it leads outside the current directory
817---   - "foo/../../bar" => "../bar"
818---   - "../../foo" => "../../foo"
819--- - ".." in the root directory returns the root directory.
820---   - "/../../" => "/"
821---
822--- On Windows, backslashes (`\`) are converted to forward slashes (`/`).
823---
824--- Examples:
825--- ```lua
826--- [[C:\Users\jdoe]]                         --> "C:/Users/jdoe"
827--- "~/src/neovim"                            --> "/home/jdoe/src/neovim"
828--- "$XDG_CONFIG_HOME/nvim/init.vim"          --> "/Users/jdoe/.config/nvim/init.vim"
829--- "~/src/nvim/api/../tui/./tui.c"           --> "/home/jdoe/src/nvim/tui/tui.c"
830--- "./foo/bar"                               --> "foo/bar"
831--- "foo/../../../bar"                        --> "../../bar"
832--- "/home/jdoe/../../../bar"                 --> "/bar"
833--- "C:foo/../../baz"                         --> "C:../baz"
834--- "C:/foo/../../baz"                        --> "C:/baz"
835--- [[\\?\UNC\server\share\foo\..\..\..\bar]] --> "//?/UNC/server/share/bar"
836--- ```
837---
838---@since 10
839---@param path (string) Path to normalize
840---@param opts? vim.fs.normalize.Opts
841---@return (string) : Normalized path
842function M.normalize(path, opts)
843  opts = opts or {}
844
845  if not opts._fast then
846    vim.validate('path', path, 'string')
847    vim.validate('plain', opts.plain, 'boolean', true)
848    vim.validate('win', opts.win, 'boolean', true)
849  end
850
851  local win = opts.win == nil and iswin or not not opts.win
852  local os_sep_local = win and '\\' or '/'
853
854  -- Empty path is already normalized
855  if path == '' then
856    return ''
857  end
858
859  if not opts.plain then
860    -- Expand ~ to user's home directory
861    path = expand_home(path, os_sep_local)
862
863    -- Expand environment variables
864    if opts.expand_env == nil or opts.expand_env then
865      path = path:gsub('%$([%w_]+)', uv.os_getenv) --- @type string
866    end
867  end
868
869  if win then
870    -- Convert path separator to `/`
871    path = path:gsub(os_sep_local, '/') --- @type string
872  end
873
874  -- Check for double slashes at the start of the path because they have special meaning
875  local double_slash = false
876  if not opts._fast then
877    double_slash = vim.startswith(path, '//') and not vim.startswith(path, '///')
878  end
879
880  local prefix = ''
881
882  if win then
883    local is_valid --- @type boolean
884    -- Split Windows paths into prefix and body to make processing easier
885    prefix, path, is_valid = split_windows_path(path)
886
887    -- If path is not valid, return it as-is
888    if not is_valid then
889      return prefix .. path
890    end
891
892    -- Ensure capital drive and remove extraneous slashes from the prefix
893    prefix = prefix:gsub('^%a:', string.upper):gsub('/+', '/')
894  end
895
896  if not opts._fast then
897    -- Resolve `.` and `..` components and remove extraneous slashes from path, then recombine prefix
898    -- and path.
899    path = path_resolve_dot(path)
900  end
901
902  -- Preserve leading double slashes as they indicate UNC paths and DOS device paths in
903  -- Windows and have implementation-defined behavior in POSIX.
904  path = (double_slash and '/' or '') .. prefix .. path
905
906  -- Change empty path to `.`
907  if path == '' then
908    path = '.'
909  end
910
911  return path
912end
913
914--- @class vim.fs.mkdir.Opts
915--- @inlinedoc
916---
917--- Create intermediate directories as necessary.
918--- (default: `false`)
919--- @field parents? boolean
920---
921--- Permission bits for newly-created directories.
922--- (default: `493`)
923--- @field mode? integer
924
925--- Creates a directory.
926---
927---@since 15
928---@param path string Path to create (not expanded/resolved).
929---@param opts? vim.fs.mkdir.Opts Optional keyword arguments.
930function M.mkdir(path, opts)
931  vim.validate('path', path, 'string')
932  vim.validate('opts', opts, 'table', true)
933  opts = opts or {}
934  vim.validate('parents', opts.parents, 'boolean', true)
935  vim.validate('mode', opts.mode, 'number', true)
936
937  vim.fn.mkdir(path, opts.parents and 'p' or '', tostring(opts.mode or 493))
938end
939
940--- @param path string Path to remove
941--- @param ty string type of path
942--- @param recursive? boolean
943--- @param force? boolean
944local function rm(path, ty, recursive, force)
945  --- @diagnostic disable-next-line:no-unknown
946  local rm_fn
947
948  if ty == 'directory' then
949    if recursive then
950      for file, fty in vim.fs.dir(path) do
951        rm(M.joinpath(path, file), fty, true, force)
952      end
953    elseif not force then
954      error(string.format('%s is a directory', path))
955    end
956
957    rm_fn = uv.fs_rmdir
958  else
959    rm_fn = uv.fs_unlink
960  end
961
962  local ret, err, errnm = rm_fn(path)
963  if ret == nil and (not force or errnm ~= 'ENOENT') then
964    error(err)
965  end
966end
967
968--- @class vim.fs.rm.Opts
969--- @inlinedoc
970---
971--- Remove directory contents recursively.
972--- @field recursive? boolean
973---
974--- Ignore nonexistent files and arguments.
975--- @field force? boolean
976
977--- Removes a file or directory.
978---
979--- Removes symlinks without touching the origin. To remove the origin, resolve it explicitly
980--- with |uv.fs_realpath()|:
981--- ```lua
982--- vim.fs.rm(vim.uv.fs_realpath('symlink-dir'), { recursive = true })
983--- ```
984---
985--- @since 13
986--- @param path string Path to remove (not expanded/resolved).
987--- @param opts? vim.fs.rm.Opts
988function M.rm(path, opts)
989  opts = opts or {}
990
991  local stat, err, errnm = uv.fs_lstat(path)
992  if stat then
993    rm(path, stat.type, opts.recursive, opts.force)
994  elseif not opts.force or errnm ~= 'ENOENT' then
995    error(err)
996  end
997end
998
999--- @class vim.fs.abspath.Opts
1000--- @inlinedoc
1001---
1002--- Resolve the path relative to this directory.
1003--- @field cwd? string
1004---
1005--- Do not expand tilde (~).
1006--- @field plain? boolean
1007
1008--- Converts `path` to an absolute path. Expands tilde (~) at the beginning of the path (unless
1009--- plain=true). Does not check if the path exists, normalize the path, resolve symlinks or
1010--- hardlinks (including "." and ".."), or expand environment variables. If the path is already
1011--- absolute, it is returned unchanged. Converts `\` path separators to `/`.
1012---
1013--- @since 13
1014--- @param path string Path
1015--- @param opts? vim.fs.abspath.Opts
1016--- @return string Absolute path
1017function M.abspath(path, opts)
1018  -- TODO(justinmk): mark f_fnamemodify as API_FAST and use it, ":p:h" should be safe...
1019  --
1020  opts = opts or {}
1021
1022  vim.validate('path', path, 'string')
1023  vim.validate('cwd', opts.cwd, 'string', true)
1024  vim.validate('plain', opts.plain, 'boolean', true)
1025
1026  -- Expand ~ to user's home directory
1027  if not opts.plain then
1028    path = expand_home(path)
1029  end
1030
1031  -- Convert path separator to `/`
1032  path = path:gsub(os_sep, '/')
1033
1034  local prefix = ''
1035
1036  if iswin then
1037    prefix, path = split_windows_path(path)
1038  end
1039
1040  if prefix == '//' or vim.startswith(path, '/') then
1041    -- Path is already absolute, do nothing
1042    return prefix .. path
1043  end
1044
1045  -- Windows allows paths like C:foo/bar, these paths are relative to the current working directory
1046  -- of the drive specified in the path
1047  local cwd =
1048    assert((iswin and prefix:match('^%w:$')) and uv.fs_realpath(prefix) or opts.cwd or uv.cwd())
1049  -- Convert cwd path separator to `/`
1050  cwd = cwd:gsub(os_sep, '/')
1051
1052  if path == '.' then
1053    return cwd
1054  end
1055  -- Prefix is not needed for expanding relative paths, `cwd` already contains it.
1056  return M.joinpath(cwd, path)
1057end
1058
1059--- Gets `target` path relative to `base`, or `nil` if `base` is not an ancestor.
1060---
1061--- Example:
1062---
1063--- ```lua
1064--- vim.fs.relpath('/var', '/var/lib') -- 'lib'
1065--- vim.fs.relpath('/var', '/usr/bin') -- nil
1066--- ```
1067---
1068--- @since 13
1069--- @param base string
1070--- @param target string
1071--- @param opts table? Reserved for future use
1072--- @return string|nil
1073function M.relpath(base, target, opts)
1074  vim.validate('base', base, 'string')
1075  vim.validate('target', target, 'string')
1076  vim.validate('opts', opts, 'table', true)
1077
1078  base = M.normalize(M.abspath(base))
1079  target = M.normalize(M.abspath(target))
1080  if base == target then
1081    return '.'
1082  end
1083
1084  local prefix = ''
1085  if iswin then
1086    prefix, base = split_windows_path(base)
1087  end
1088  base = prefix .. base .. (base ~= '/' and '/' or '')
1089
1090  return vim.startswith(target, base) and target:sub(#base + 1) or nil
1091end
1092
1093--- Return the file's last extension, if any.
1094---
1095--- Similar to |fnamemodify()| with the |::e| modifier. The extension does not include a leading
1096--- period.
1097---
1098--- Examples:
1099---
1100--- ```lua
1101--- vim.fs.ext('archive.tar.gz') -- 'gz'
1102--- vim.fs.ext('~/.git') -- ''
1103--- vim.fs.ext('plugin/myplug.lua') -- 'lua'
1104--- ```
1105---
1106---@since 14
1107---@param file string Path
1108---@param opts table? Reserved for future use
1109---@return string Extension of {file}
1110function M.ext(file, opts)
1111  vim.validate('file', file, 'string')
1112  vim.validate('opts', opts, 'table', true)
1113  return vim.fn.fnamemodify(file, ':e')
1114end
1115
1116return M