robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ) 74return function ( _ , dir ) 75local parent =M . dirname ( dir ) 76if parent == dir then 77return nil 78end 79 80return parent 81end , 82nil , 83start 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 ) 93if file == nil then 94return nil 95end 96vim . validate ( 'file' , file , 'string' ) 97--- @cast file string 98local dir =vim . fn . fnamemodify ( file , ':h' ) 99if iswin then 100return ( dir : gsub ( os_sep , '/' )) 101end 102return 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 ) 112if file == nil then 113return nil 114end 115vim . validate ( 'file' , file , 'string' ) 116--- @cast file string 117local name =vim . fn . fnamemodify ( file , ':t' ) 118if iswin then 119return ( name : gsub ( os_sep , '/' )) 120end 121return 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 ( ... ) 137local n =select ( '#' , ... ) 138---@type string[] 139local segments ={} 140for i =1 , n do 141local s =select ( i , ... ) 142if s and # s > 0 then 143segments [ # segments + 1 ] =s 144end 145end 146 147local path =table . concat ( segments , '/' ) 148 149return ( 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 ) 182vim . validate ( 'path' , path , 'string' ) 183opts =opts or {} 184vim . validate ( 'maxlen' , opts . maxlen , function ( v ) 185return type ( v ) == 'number' and v >= 8 186end , true , '`opts.maxlen` must be >= 8' ) 187local maxlen =opts . maxlen or 180 188 189-- Capture URI scheme before normalize() collapses "://" to ":/" (which looks like "C:/") 190local 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 193path =vim . fs . normalize ( path , { plain =true } ) 194local s =path 195 196if uri_scheme then 197-- Replace scheme prefix with "=uri-{scheme}-" 198s ='=uri-' .. uri_scheme .. '-' .. s : sub ( # uri_scheme + 3 ) -- `+ 3` skips`:/` 199elseif 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 202s =vim . fn . fnamemodify ( s , ':~' ) 203end 204 205-- Replace UNC `//...` (Windows only) with `=unc-` 206-- `//?/` and `//./` are NT namespace prefixes, not UNC 207if 208iswin 209and vim . startswith ( s , '//' ) 210and not vim . startswith ( s , '//?/' ) 211and not vim . startswith ( s , '//./' ) 212then 213s ='=unc-' .. s : sub ( 3 ) 214end 215 216-- Sanitize unsafe chars and trim trailing "-" and "." 217s =s : gsub ( '[%c%s/\\:*?"<>|]' , '-' ) 218s =s : gsub ( '[.-]+$' , '' ) 219-- Strip the leading "-" from an absolute path 220s =s : gsub ( '^-' , '' ) 221 222-- Always compute the hash to prevent collisions 223local hash8 =vim . fn . sha256 ( path ): sub ( 1 , 8 ) 224 225-- Fully scrubbed path uses the reserved prefix 226if s == '' then 227s ='=special' 228end 229 230-- Within maxlen: "{name}-{hash8}" 231if # s + 1 + # hash8 <= maxlen then 232return s .. '-' .. hash8 233end 234 235-- "{head}~~~{tail}-{hash8}" 236local budget =maxlen - 12 -- 3 for "~~~", 1 for "-", 8 for hash 237if budget < 1 then 238-- No room for a readable form: degrade to a plain hash (maxlen >= 8 == #hash8). 239return hash8 240end 241local head_len =math . floor ( budget / 3 ) 242local h =( 243s : sub ( 1 , head_len ): match ( '^.*()-' ) --[[@as integer?]] 244) or head_len -- byte position where {head} ends 245if 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. 249local char_start =h + vim . str_utf_start ( s , h ) ---@type integer 250if char_start + vim . str_utf_end ( s , char_start ) > h then 251h =char_start - 1 252end 253end 254-- Always in [h + 4, #s]: the "{name}-{hash8}" case above handled #s <= budget + 3. 255local tail_start =# s - budget + h + 1 256local 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 258if t == tail_start then 259local offset_start =vim . str_utf_start ( s , t ) 260if offset_start < 0 then 261local char_start =t + offset_start ---@type integer 262t =char_start + vim . str_utf_end ( s , char_start ) + 1 263end 264end 265return 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 276local name , etype =uv . fs_scandir_next ( fs ) 277 278if not name then 279return 280end 281 282if etype == nil then 283local stat =uv . fs_lstat ( M . joinpath ( path , name )) 284-- Workaround #39612 https://github.com/luvit/luv/issues/660 285etype =stat and stat . type or 'unknown' 286end 287 288return 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 ) 338opts =opts or {} 339 340vim . validate ( 'path' , path , 'string' ) 341vim . validate ( 'depth' , opts . depth , 'number' , true ) 342vim . validate ( 'err' , opts . err , 'boolean' , true ) 343vim . validate ( 'follow' , opts . follow , 'boolean' , true ) 344vim . validate ( 'skip' , opts . skip , 'function' , true ) 345vim . validate ( 'plain' , opts . plain , 'boolean' , true ) 346 347path =M . normalize ( path , { plain =opts . plain } ) 348 349local rootfs , rooterr =uv . fs_scandir ( path ) 350 351if 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. 355local done =not opts . err 356return function () 357if done then 358return nil 359end 360done =true 361return path , nil , rooterr 362end 363end 364 365if not opts . depth or opts . depth == 1 then 366return function () 367return fs_scandir_next ( rootfs , path ) 368end 369end 370 371--- @async 372return coroutine . wrap ( function () 373---@type [string, integer, uv.uv_fs_t][] 374local dirs ={ { path , 1 , rootfs } } 375while # dirs > 0 do 376--- @type string, integer, any 377local dir0 , level , fs =unpack ( table . remove ( dirs , 1 )) 378local dir =level == 1 and dir0 or M . joinpath ( path , dir0 ) 379while fs do 380local name , t =fs_scandir_next ( fs , dir ) 381if not name then 382break 383end 384local f =level == 1 and name or M . joinpath ( dir0 , name ) 385local err_scan =nil 386if 387opts . depth 388and level < opts . depth 389and ( t == 'directory' or ( t == 'link' and opts . follow and ( 390uv . fs_stat ( M . joinpath ( path , f )) or {} 391). type == 'directory' )) 392and ( not opts . skip or opts . skip ( f ) ~= false ) 393then 394local fs_next , err =uv . fs_scandir ( M . joinpath ( path , f )) 395if not fs_next then 396err_scan =opts . err and err or nil 397else 398dirs [ # dirs + 1 ] ={ f , level + 1 , fs_next } 399end 400end 401coroutine . yield ( f , t , err_scan ) 402end 403end 404end ) 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 ) 471opts =opts or {} 472vim . validate ( 'names' , names , { 'string' , 'table' , 'function' } ) 473vim . validate ( 'path' , opts . path , 'string' , true ) 474vim . validate ( 'upward' , opts . upward , 'boolean' , true ) 475vim . validate ( 'stop' , opts . stop , 'string' , true ) 476vim . validate ( 'type' , opts . type , 'string' , true ) 477vim . validate ( 'limit' , opts . limit , 'number' , true ) 478vim . validate ( 'follow' , opts . follow , 'boolean' , true ) 479 480if type ( names ) == 'string' then 481names ={ names } 482end 483 484local path =opts . path or assert ( uv . cwd ()) 485local stop =opts . stop 486local limit =opts . limit or 1 487 488local matches ={} --- @type string[] 489local errors ={} --- @type string[] 490 491--- @param match string 492local function add ( match ) 493matches [ # matches + 1 ] =M . normalize ( match ) 494if # matches == limit then 495return true 496end 497end 498 499if opts . upward then 500if path == stop then 501return matches , errors 502end 503 504local test --- @type fun(p: string): string[] 505 506if type ( names ) == 'function' then 507--- @param p string 508test =function ( p ) 509local t ={} 510for name , type , err in M . dir ( p , { err =true } ) do 511if err ~= nil then 512table . insert ( errors , err ) 513elseif ( not opts . type or opts . type == type ) and names ( name , p ) then 514table . insert ( t , M . joinpath ( p , name )) 515end 516end 517return t 518end 519else 520--- @param p string 521test =function ( p ) 522local t ={} --- @type string[] 523local ok , aerr =uv . fs_access ( p , 'R' ) -- Check if the root dir is readable. 524if not ok then 525table . insert ( errors , aerr ) 526return t 527end 528for _ , name in ipairs ( names ) do 529local f =M . joinpath ( p , name ) 530local stat =uv . fs_stat ( f ) 531if stat and ( not opts . type or opts . type == stat . type ) then 532t [ # t + 1 ] =f 533end 534end 535 536return t 537end 538end 539 540for _ , match in ipairs ( test ( path )) do 541if add ( match ) then 542return matches , errors 543end 544end 545 546for parent in M . parents ( path ) do 547if stop and parent == stop then 548break 549end 550 551for _ , match in ipairs ( test ( parent )) do 552if add ( match ) then 553return matches , errors 554end 555end 556end 557else 558local dirs ={ path } 559while # dirs > 0 do 560local dir =table . remove ( dirs , 1 ) 561if stop and dir == stop then 562break 563end 564 565for other , type_ , err in M . dir ( dir , { err =true } ) do 566if err ~= nil then 567table . insert ( errors , err ) 568else 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. 571if type ( names ) == 'function' then 572if ( not opts . type or opts . type == type_ ) and names ( other , dir ) then 573if add ( M . joinpath ( dir , other )) then 574return matches , errors 575end 576end 577else 578for _ , name in ipairs ( names ) do 579if name == other and ( not opts . type or opts . type == type_ ) then 580if add ( M . joinpath ( dir , other )) then 581return matches , errors 582end 583end 584end 585end 586 587if type_ == 'directory' or ( type_ == 'link' and opts . follow ) then 588local f =M . joinpath ( dir , other ) 589if type_ == 'directory' or ( uv . fs_stat ( f ) or {} ). type == 'directory' then 590dirs [ # dirs + 1 ] =f 591end 592end 593end 594end 595end 596end 597 598return 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 ) 638vim . validate ( 'source' , source , { 'number' , 'string' } ) 639vim . validate ( 'marker' , marker , { 'string' , 'table' , 'function' } ) 640 641local path ---@type string 642if type ( source ) == 'string' then 643path =source 644elseif type ( source ) == 'number' then 645if vim . bo [ source ]. buftype ~= '' then 646path =assert ( uv . cwd ()) 647else 648path =vim . api . nvim_buf_get_name ( source ) 649end 650else 651error ( 'invalid type for argument "source": expected string or buffer number' ) 652end 653 654local markers =type ( marker ) == 'table' and marker or { marker } 655for _ , mark in ipairs ( markers ) do 656local paths =M . find ( mark , { 657upward =true , 658path =M . abspath ( path ), 659} ) 660 661if # paths ~= 0 then 662local dir =M . dirname ( paths [ 1 ]) 663return dir and M . abspath ( dir ) or nil 664end 665end 666 667return 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 ) 685local 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 692local function match_to_prefix ( pattern ) 693local match =path : match ( pattern ) 694 695if match then 696prefix =prefix .. match --[[ @as string ]] 697path =path : sub ( # match + 1 ) 698end 699 700return match 701end 702 703local function process_unc_path () 704return match_to_prefix ( '[^/]+/+[^/]+/+' ) 705end 706 707if match_to_prefix ( '^//[?.]/' ) then 708-- Device paths 709local 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 712if not device or ( device : match ( '^UNC/+$' ) and not process_unc_path ()) then 713return prefix , path , false 714end 715elseif match_to_prefix ( '^//' ) then 716-- Process UNC path, return early if it's invalid 717if not process_unc_path () then 718return prefix , path , false 719end 720elseif path : match ( '^%w:' ) then 721-- Drive paths 722prefix , path =path : sub ( 1 , 2 ), path : sub ( 3 ) 723end 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. 728local trailing_slash =prefix : match ( '/+$' ) 729 730if trailing_slash then 731prefix =prefix : sub ( 1 , - 1 - # trailing_slash ) 732path =trailing_slash .. path --[[ @as string ]] 733end 734 735return 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 ) 746local is_path_absolute =vim . startswith ( path , '/' ) 747local new_path_components ={} 748 749for component in vim . gsplit ( path , '/' ) do 750if component == '.' or component == '' then -- luacheck: ignore 542 751-- Skip `.` components and empty components 752elseif component == '..' then 753if # 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 756table . remove ( new_path_components ) 757elseif is_path_absolute then -- luacheck: ignore 542 758-- Reached the root directory in absolute path, do nothing 759else 760-- Reached current directory in relative path, add `..` to the path 761table . insert ( new_path_components , component ) 762end 763else 764table . insert ( new_path_components , component ) 765end 766end 767 768return ( 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 ) 777sep =sep or os_sep 778 779if vim . startswith ( path , '~' ) then 780local home =uv . os_homedir () or '~' --- @type string 781 782if home : sub ( - 1 ) == sep then 783home =home : sub ( 1 , - 2 ) 784end 785 786path =home .. path : sub ( 2 ) --- @type string 787end 788 789return 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 ) 843opts =opts or {} 844 845if not opts . _fast then 846vim . validate ( 'path' , path , 'string' ) 847vim . validate ( 'plain' , opts . plain , 'boolean' , true ) 848vim . validate ( 'win' , opts . win , 'boolean' , true ) 849end 850 851local win =opts . win == nil and iswin or not not opts . win 852local os_sep_local =win and '\\' or '/' 853 854-- Empty path is already normalized 855if path == '' then 856return '' 857end 858 859if not opts . plain then 860-- Expand ~ to user's home directory 861path =expand_home ( path , os_sep_local ) 862 863-- Expand environment variables 864if opts . expand_env == nil or opts . expand_env then 865path =path : gsub ( '%$([%w_]+)' , uv . os_getenv ) --- @type string 866end 867end 868 869if win then 870-- Convert path separator to `/` 871path =path : gsub ( os_sep_local , '/' ) --- @type string 872end 873 874-- Check for double slashes at the start of the path because they have special meaning 875local double_slash =false 876if not opts . _fast then 877double_slash =vim . startswith ( path , '//' ) and not vim . startswith ( path , '///' ) 878end 879 880local prefix ='' 881 882if win then 883local is_valid --- @type boolean 884-- Split Windows paths into prefix and body to make processing easier 885prefix , path , is_valid =split_windows_path ( path ) 886 887-- If path is not valid, return it as-is 888if not is_valid then 889return prefix .. path 890end 891 892-- Ensure capital drive and remove extraneous slashes from the prefix 893prefix =prefix : gsub ( '^%a:' , string . upper ): gsub ( '/+' , '/' ) 894end 895 896if not opts . _fast then 897-- Resolve `.` and `..` components and remove extraneous slashes from path, then recombine prefix 898-- and path. 899path =path_resolve_dot ( path ) 900end 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. 904path =( double_slash and '/' or '' ) .. prefix .. path 905 906-- Change empty path to `.` 907if path == '' then 908path ='.' 909end 910 911return 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 ) 931vim . validate ( 'path' , path , 'string' ) 932vim . validate ( 'opts' , opts , 'table' , true ) 933opts =opts or {} 934vim . validate ( 'parents' , opts . parents , 'boolean' , true ) 935vim . validate ( 'mode' , opts . mode , 'number' , true ) 936 937vim . 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 946local rm_fn 947 948if ty == 'directory' then 949if recursive then 950for file , fty in vim . fs . dir ( path ) do 951rm ( M . joinpath ( path , file ), fty , true , force ) 952end 953elseif not force then 954error ( string . format ( '%s is a directory' , path )) 955end 956 957rm_fn =uv . fs_rmdir 958else 959rm_fn =uv . fs_unlink 960end 961 962local ret , err , errnm =rm_fn ( path ) 963if ret == nil and ( not force or errnm ~= 'ENOENT' ) then 964error ( err ) 965end 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 ) 989opts =opts or {} 990 991local stat , err , errnm =uv . fs_lstat ( path ) 992if stat then 993rm ( path , stat . type , opts . recursive , opts . force ) 994elseif not opts . force or errnm ~= 'ENOENT' then 995error ( err ) 996end 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-- 1020opts =opts or {} 1021 1022vim . validate ( 'path' , path , 'string' ) 1023vim . validate ( 'cwd' , opts . cwd , 'string' , true ) 1024vim . validate ( 'plain' , opts . plain , 'boolean' , true ) 1025 1026-- Expand ~ to user's home directory 1027if not opts . plain then 1028path =expand_home ( path ) 1029end 1030 1031-- Convert path separator to `/` 1032path =path : gsub ( os_sep , '/' ) 1033 1034local prefix ='' 1035 1036if iswin then 1037prefix , path =split_windows_path ( path ) 1038end 1039 1040if prefix == '//' or vim . startswith ( path , '/' ) then 1041-- Path is already absolute, do nothing 1042return prefix .. path 1043end 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 1047local cwd = 1048assert (( iswin and prefix : match ( '^%w:$' )) and uv . fs_realpath ( prefix ) or opts . cwd or uv . cwd ()) 1049-- Convert cwd path separator to `/` 1050cwd =cwd : gsub ( os_sep , '/' ) 1051 1052if path == '.' then 1053return cwd 1054end 1055-- Prefix is not needed for expanding relative paths, `cwd` already contains it. 1056return 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 ) 1074vim . validate ( 'base' , base , 'string' ) 1075vim . validate ( 'target' , target , 'string' ) 1076vim . validate ( 'opts' , opts , 'table' , true ) 1077 1078base =M . normalize ( M . abspath ( base )) 1079target =M . normalize ( M . abspath ( target )) 1080if base == target then 1081return '.' 1082end 1083 1084local prefix ='' 1085if iswin then 1086prefix , base =split_windows_path ( base ) 1087end 1088base =prefix .. base .. ( base ~= '/' and '/' or '' ) 1089 1090return 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 ) 1111vim . validate ( 'file' , file , 'string' ) 1112vim . validate ( 'opts' , opts , 'table' , true ) 1113return vim . fn . fnamemodify ( file , ':e' ) 1114end 1115 1116return M