robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
35.7 KiB1045 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, before_each, after_each, setup, finally =
5  t.describe, t.it, t.before_each, t.after_each, t.setup, t.finally
6local clear = n.clear
7local exec_lua = n.exec_lua
8local eq = t.eq
9local eq_paths = t.eq_paths
10local mkdir_p = n.mkdir_p
11local rmdir = n.rmdir
12local nvim_dir = n.nvim_dir
13local command = n.command
14local api = n.api
15local fn = n.fn
16local test_build_dir = t.paths.test_build_dir
17local test_source_path = t.paths.test_source_path
18local nvim_prog = n.nvim_prog
19local is_os = t.is_os
20local mkdir = t.mkdir
21
22local nvim_prog_basename = is_os('win') and 'nvim.exe' or 'nvim'
23
24local link_limit = is_os('win') and 64 or (is_os('mac') or is_os('bsd')) and 33 or 41
25
26local test_basename_dirname_eq = {
27  '~/foo/',
28  '~/foo',
29  '~/foo/bar.lua',
30  'foo.lua',
31  ' ',
32  '',
33  '.',
34  '..',
35  '../',
36  '~',
37  '/usr/bin',
38  '/usr/bin/gcc',
39  '/',
40  '/usr/',
41  '/usr',
42  'c:/usr',
43  'c:/',
44  'c:',
45  'c:/users/foo',
46  'c:/users/foo/bar.lua',
47  'c:/users/foo/bar/../',
48  '~/foo/bar\\baz',
49}
50
51local tests_windows_paths = {
52  'c:\\usr',
53  'c:\\',
54  'c:',
55  'c:\\users\\foo',
56  'c:\\users\\foo\\bar.lua',
57  'c:\\users\\foo\\bar\\..\\',
58}
59
60setup(clear)
61
62describe('vim.fs', function()
63  describe('parents()', function()
64    it('works', function()
65      local test_dir = nvim_dir .. '/test'
66      mkdir_p(test_dir)
67      local dirs = {} --- @type string[]
68      for dir in vim.fs.parents(test_dir .. '/foo.txt') do
69        dirs[#dirs + 1] = dir
70        if dir == test_build_dir then
71          break
72        end
73      end
74      eq({ test_dir, nvim_dir, test_build_dir }, dirs)
75      rmdir(test_dir)
76    end)
77  end)
78
79  describe('dirname()', function()
80    it('works', function()
81      eq(test_build_dir, vim.fs.dirname(nvim_dir))
82
83      ---@param paths string[]
84      ---@param is_win? boolean
85      local function test_paths(paths, is_win)
86        local gsub = is_win and [[:gsub('\\', '/')]] or ''
87        local code = string.format(
88          [[
89          local path = ...
90          return vim.fn.fnamemodify(path,':h')%s
91        ]],
92          gsub
93        )
94
95        for _, path in ipairs(paths) do
96          eq(exec_lua(code, path), vim.fs.dirname(path), path)
97        end
98      end
99
100      test_paths(test_basename_dirname_eq)
101      if is_os('win') then
102        test_paths(tests_windows_paths, true)
103      end
104    end)
105
106    it('trims redundant slashes #37698', function()
107      eq('/name', vim.fs.dirname('/name//////////'))
108    end)
109  end)
110
111  describe('basename()', function()
112    it('works', function()
113      eq(nvim_prog_basename, vim.fs.basename(nvim_prog))
114
115      ---@param paths string[]
116      ---@param is_win? boolean
117      local function test_paths(paths, is_win)
118        local gsub = is_win and [[:gsub('\\', '/')]] or ''
119        local code = string.format(
120          [[
121          local path = ...
122          return vim.fn.fnamemodify(path,':t')%s
123        ]],
124          gsub
125        )
126
127        for _, path in ipairs(paths) do
128          eq(exec_lua(code, path), vim.fs.basename(path), path)
129        end
130      end
131
132      test_paths(test_basename_dirname_eq)
133      if is_os('win') then
134        test_paths(tests_windows_paths, true)
135      end
136    end)
137
138    it('trims redundant slashes #37698', function()
139      -- XXX: for better or worse, this matches python's `os.path.basename`.
140      -- https://github.com/neovim/neovim/issues/37698#issuecomment-3847866806
141      eq('', vim.fs.basename('/name//////////'))
142    end)
143  end)
144
145  describe('dir()', function()
146    before_each(function()
147      mkdir('testd')
148      mkdir('testd/a')
149      mkdir('testd/a/b')
150      mkdir('testd/a/b/c')
151    end)
152
153    after_each(function()
154      rmdir('testd')
155    end)
156
157    it('works', function()
158      eq(
159        true,
160        exec_lua(function()
161          for name, type in vim.fs.dir(nvim_dir) do
162            if name == nvim_prog_basename and type == 'file' then
163              return true
164            end
165          end
166          return false
167        end)
168      )
169    end)
170
171    it('works with opts.depth, opts.skip and opts.follow', function()
172      io.open('testd/a1', 'w'):close()
173      io.open('testd/b1', 'w'):close()
174      io.open('testd/c1', 'w'):close()
175      io.open('testd/a/a2', 'w'):close()
176      io.open('testd/a/b2', 'w'):close()
177      io.open('testd/a/c2', 'w'):close()
178      io.open('testd/a/b/a3', 'w'):close()
179      io.open('testd/a/b/b3', 'w'):close()
180      io.open('testd/a/b/c3', 'w'):close()
181      io.open('testd/a/b/c/a4', 'w'):close()
182      io.open('testd/a/b/c/b4', 'w'):close()
183      io.open('testd/a/b/c/c4', 'w'):close()
184
185      local function run(dir, depth, skip, follow)
186        return exec_lua(function(follow_)
187          local r = {} --- @type table<string, string>
188          local skip_f --- @type function
189          if skip then
190            skip_f = function(n0)
191              if vim.tbl_contains(skip or {}, n0) then
192                return false
193              end
194            end
195          end
196          for name, type_ in vim.fs.dir(dir, { depth = depth, skip = skip_f, follow = follow_ }) do
197            r[name] = type_
198          end
199          return r
200        end, follow)
201      end
202
203      local exp = {}
204
205      exp['a1'] = 'file'
206      exp['b1'] = 'file'
207      exp['c1'] = 'file'
208      exp['a'] = 'directory'
209
210      eq(exp, run('testd', 1))
211
212      exp['a/a2'] = 'file'
213      exp['a/b2'] = 'file'
214      exp['a/c2'] = 'file'
215      exp['a/b'] = 'directory'
216      local lexp = vim.deepcopy(exp)
217
218      eq(exp, run('testd', 2))
219
220      exp['a/b/a3'] = 'file'
221      exp['a/b/b3'] = 'file'
222      exp['a/b/c3'] = 'file'
223      exp['a/b/c'] = 'directory'
224
225      eq(exp, run('testd', 3))
226      eq(exp, run('testd', 999, { 'a/b/c' }))
227
228      exp['a/b/c/a4'] = 'file'
229      exp['a/b/c/b4'] = 'file'
230      exp['a/b/c/c4'] = 'file'
231
232      eq(exp, run('testd', 999))
233
234      vim.uv.fs_symlink(vim.uv.fs_realpath('testd/a'), 'testd/l', { junction = true, dir = true })
235      lexp['l'] = 'link'
236      eq(lexp, run('testd', 2, nil, false))
237
238      lexp['l/a2'] = 'file'
239      lexp['l/b2'] = 'file'
240      lexp['l/c2'] = 'file'
241      lexp['l/b'] = 'directory'
242      eq(lexp, run('testd', 2, nil, true))
243    end)
244
245    it('follow=true handles symlink loop', function()
246      local cwd = 'testd/a/b/c'
247      local symlink = cwd .. '/link_loop' ---@type string
248      vim.uv.fs_symlink(vim.uv.fs_realpath(cwd), symlink, { junction = true, dir = true })
249
250      eq(
251        link_limit,
252        exec_lua(function()
253          return #vim.iter(vim.fs.dir(cwd, { depth = math.huge, follow = true })):totable()
254        end)
255      )
256    end)
257
258    describe('fs_scandir_next fallback', function()
259      before_each(function()
260        mkdir('testdir')
261        t.write_file('testdir/test.txt', 'test file')
262      end)
263
264      after_each(function()
265        rmdir('testdir')
266      end)
267
268      it('falls back to fs_lstat when fs_scandir_next returns nil type', function()
269        local result = n.exec_lua([[
270          local orig = vim.uv.fs_scandir_next
271
272          vim.uv.fs_scandir_next = function(fs)
273            local name = orig(fs)
274            if name then
275              return name, nil
276            end
277            return name
278          end
279
280          local out = {}
281          for name, etype in vim.fs.dir('testdir') do
282            out[name] = etype
283          end
284
285          vim.uv.fs_scandir_next = orig
286          return out
287        ]])
288
289        eq('file', result['test.txt'])
290      end)
291    end)
292
293    it('reports errors', function()
294      mkdir('testdir')
295      mkdir('testdir/noaccess')
296      mkdir('testdir/a')
297      mkdir('testdir/a/noaccess')
298      finally(function()
299        rmdir('testdir')
300      end)
301
302      -- With opts.err=false: errors are silent, unreadable root looks empty.
303      eq(
304        0,
305        exec_lua(function()
306          local n0 = 0
307          for _ in vim.fs.dir('does-not-exist') do
308            n0 = n0 + 1
309          end
310          return n0
311        end)
312      )
313
314      -- With opts.err=true: unreadable root dir yields a single (name, nil, err).
315      eq(
316        { name = 'does-not-exist', err = 'ENOENT: no such file or directory: does-not-exist' },
317        exec_lua(function()
318          for name, type, err in vim.fs.dir('does-not-exist', { err = true }) do
319            return { name = name, type = type, err = err }
320          end
321        end)
322      )
323
324      -- With opts.err=true: unreadable child dir.
325      local result = exec_lua(function()
326        -- Stub fs_scandir since chmod doesn't work reliably on Windows.
327        local orig_scandir = vim.uv.fs_scandir
328        vim.uv.fs_scandir = function(path, ...)
329          if path == 'testdir/noaccess' then
330            return nil, 'EACCES: permission denied: testdir/noaccess'
331          end
332          return orig_scandir(path, ...)
333        end
334
335        local errors = {} ---@type table<string, string>
336        for f, _, err in vim.fs.dir('testdir', { depth = 2, err = true }) do
337          errors[f] = err
338        end
339
340        vim.uv.fs_scandir = orig_scandir
341        return errors
342      end)
343      eq('EACCES: permission denied: testdir/noaccess', result['noaccess'])
344      -- nil: with depth=2 we don't scan testdir/a/noaccess.
345      eq(nil, result['a/noaccess'])
346    end)
347
348    it('plain=true', function()
349      mkdir('testdir')
350      mkdir('testdir/$XTEST_FS_DIR')
351      mkdir('testdir/expanded')
352      t.write_file('testdir/$XTEST_FS_DIR/literal.txt', '')
353      t.write_file('testdir/expanded/expanded.txt', '')
354      finally(function()
355        rmdir('testdir')
356      end)
357
358      eq(
359        { { ['expanded.txt'] = 'file' }, { ['literal.txt'] = 'file' } },
360        exec_lua(function()
361          vim.uv.os_setenv('XTEST_FS_DIR', 'expanded')
362          local out = {} ---@type table<string, string>[]
363          for i, plain in ipairs({ false, true }) do
364            out[i] = {}
365            for name, etype in vim.fs.dir('testdir/$XTEST_FS_DIR', { plain = plain }) do
366              out[i][name] = etype
367            end
368          end
369          return out
370        end)
371      )
372    end)
373  end)
374
375  describe('find()', function()
376    it('works', function()
377      eq(
378        { test_build_dir .. '/bin' },
379        vim.fs.find('bin', { path = nvim_dir, upward = true, type = 'directory' })
380      )
381      eq({ nvim_prog }, vim.fs.find(nvim_prog_basename, { path = test_build_dir, type = 'file' }))
382
383      local parent, name = nvim_dir:match('^(.*/)([^/]+)$')
384      eq({ nvim_dir }, vim.fs.find(name, { path = parent, upward = true, type = 'directory' }))
385    end)
386
387    -- Isolated scratch tree (not the repo) so the result is deterministic regardless of what else
388    -- sits under the source path (e.g. extra "build*/" dirs).
389    it('follows symlinks', function()
390      local root = t.tmpname(false)
391      mkdir(root)
392      -- realpath() so a symlinked tmpdir (macOS /tmp -> /private/tmp) doesn't consume a hop.
393      root = vim.fs.normalize(assert(vim.uv.fs_realpath(root)))
394      mkdir(root .. '/real')
395      t.write_file(root .. '/real/target', '')
396      -- Directory symlink: follow=true descends into it, follow=false does not.
397      vim.uv.fs_symlink(root .. '/real', root .. '/lnk', { junction = true, dir = true })
398
399      local function find(follow)
400        local r = vim.fs.find('target', {
401          path = root,
402          type = 'file',
403          limit = math.huge,
404          follow = follow,
405        })
406        table.sort(r)
407        return r
408      end
409
410      eq({ root .. '/lnk/target', root .. '/real/target' }, find(true))
411      eq({ root .. '/real/target' }, find(false))
412    end)
413
414    it('follow=true handles symlink loop', function()
415      local root = t.tmpname(false)
416      mkdir(root)
417      root = assert(vim.uv.fs_realpath(root))
418      t.write_file(root .. '/target', '')
419      -- Self-referential loop: follow=true must terminate at the OS symlink-follow limit,
420      -- yielding one hit per loop level.
421      vim.uv.fs_symlink(root, root .. '/loop', { junction = true, dir = true })
422
423      eq(link_limit, #vim.fs.find('target', {
424        path = root,
425        type = 'file',
426        limit = math.huge,
427        follow = true,
428      }))
429    end)
430
431    it('accepts predicate as names', function()
432      local opts = { path = nvim_dir, upward = true, type = 'directory' }
433      eq(
434        { test_build_dir .. '/bin' },
435        vim.fs.find(function(x)
436          return x == 'bin'
437        end, opts)
438      )
439      eq(
440        { nvim_prog },
441        vim.fs.find(function(x)
442          return x == nvim_prog_basename
443        end, { path = test_build_dir, type = 'file' })
444      )
445      eq(
446        {},
447        vim.fs.find(function(x)
448          return x == 'no-match'
449        end, opts)
450      )
451
452      opts = { path = test_source_path .. '/contrib', limit = math.huge }
453      eq(
454        exec_lua(function()
455          return vim.tbl_map(
456            vim.fs.basename,
457            vim.fn.glob(test_source_path .. '/contrib/*', false, true)
458          )
459        end),
460        vim.tbl_map(
461          vim.fs.basename,
462          vim.fs.find(function(_, d)
463            return d:match('[\\/]contrib$')
464          end, opts)
465        )
466      )
467    end)
468
469    it('reports errors', function()
470      mkdir('testdir')
471      mkdir('testdir/noaccess')
472      mkdir('testdir/a')
473      mkdir('testdir/a/noaccess')
474      t.write_file('testdir/a/match.lua', '')
475      finally(function()
476        rmdir('testdir')
477      end)
478
479      -- Scenarios run in a shared setup(clear) so the fs_scandir/fs_access stubs (chmod is unreliable on
480      -- Windows) are installed and restored.
481      local res = exec_lua(function()
482        local orig_scandir = vim.uv.fs_scandir
483        local orig_access = vim.uv.fs_access
484        local function is_blocked(path)
485          for _, prefix in ipairs({ 'testdir/noaccess', 'testdir/a/noaccess' }) do
486            if path == prefix or vim.startswith(path, prefix .. '/') then
487              return true
488            end
489          end
490          return false
491        end
492        vim.uv.fs_scandir = function(path, ...)
493          if is_blocked(path) then
494            return nil, 'EACCES: permission denied: ' .. path
495          end
496          return orig_scandir(path, ...)
497        end
498        vim.uv.fs_access = function(path, ...)
499          if is_blocked(path) then
500            return nil, 'EACCES: permission denied: ' .. path
501          end
502          return orig_access(path, ...)
503        end
504
505        local r = {}
506        r.nonexistent = { vim.fs.find('foo', { path = 'does-not-exist' }) }
507        r.unreadable_root = { vim.fs.find('foo', { path = 'testdir/noaccess' }) }
508        local dmatches, derrors =
509          vim.fs.find('match.lua', { path = 'testdir', limit = math.huge, type = 'file' })
510        table.sort(derrors) -- readdir order is not deterministic
511        r.downward = { dmatches, derrors }
512        r.upward = select(
513          2,
514          vim.fs.find('match.lua', {
515            path = 'testdir/noaccess/x',
516            upward = true,
517            stop = 'testdir',
518          })
519        )
520
521        vim.uv.fs_scandir = orig_scandir
522        vim.uv.fs_access = orig_access
523        return r
524      end)
525
526      -- Nonexistent / unreadable root path: no matches, one error.
527      eq({ {}, { 'ENOENT: no such file or directory: does-not-exist' } }, res.nonexistent)
528      eq({ {}, { 'EACCES: permission denied: testdir/noaccess' } }, res.unreadable_root)
529
530      -- Downward search collects child errors, yet still returns the match found elsewhere.
531      eq({
532        { 'testdir/a/match.lua' },
533        {
534          'EACCES: permission denied: testdir/a/noaccess',
535          'EACCES: permission denied: testdir/noaccess',
536        },
537      }, res.downward)
538
539      -- Upward search reports an error for each unreadable ancestor, in traversal order.
540      eq({
541        'EACCES: permission denied: testdir/noaccess/x',
542        'EACCES: permission denied: testdir/noaccess',
543      }, res.upward)
544    end)
545  end)
546
547  describe('root()', function()
548    before_each(function()
549      command('edit test/functional/fixtures/tty-test.c')
550    end)
551
552    after_each(function()
553      command('bwipe!')
554    end)
555
556    it('works with a single marker', function()
557      eq_paths(test_source_path, exec_lua([[return vim.fs.root(0, 'CMakePresets.json')]]))
558    end)
559
560    it('works with multiple markers', function()
561      local bufnr = api.nvim_get_current_buf()
562      eq_paths(
563        vim.fs.joinpath(test_source_path, 'test/functional/fixtures'),
564        exec_lua([[return vim.fs.root(..., {'CMakeLists.txt', 'CMakePresets.json'})]], bufnr)
565      )
566    end)
567
568    it('nested markers have equal priority', function()
569      local bufnr = api.nvim_get_current_buf()
570      eq_paths(
571        vim.fs.joinpath(test_source_path, 'test/functional'),
572        exec_lua(
573          [[return vim.fs.root(..., { 'example_spec.lua', {'CMakeLists.txt', 'CMakePresets.json'}, '.luarc.json'})]],
574          bufnr
575        )
576      )
577      eq_paths(
578        vim.fs.joinpath(test_source_path, 'test/functional/fixtures'),
579        exec_lua(
580          [[return vim.fs.root(..., { {'CMakeLists.txt', 'CMakePresets.json'}, 'example_spec.lua', '.luarc.json'})]],
581          bufnr
582        )
583      )
584      eq_paths(
585        vim.fs.joinpath(test_source_path, 'test/functional/fixtures'),
586        exec_lua(
587          [[return vim.fs.root(..., {
588              function(name, _)
589                return name:match('%.txt$')
590              end,
591              'example_spec.lua',
592              '.luarc.json' })]],
593          bufnr
594        )
595      )
596    end)
597
598    it('works with a function', function()
599      ---@type string
600      local result = exec_lua(function()
601        return vim.fs.root(0, function(name, _)
602          return name:match('%.txt$')
603        end)
604      end)
605      eq_paths(vim.fs.joinpath(test_source_path, 'test/functional/fixtures'), result)
606    end)
607
608    it('works with a filename argument', function()
609      eq(test_source_path, exec_lua([[return vim.fs.root(..., 'CMakePresets.json')]], nvim_prog))
610    end)
611
612    it('works with a relative path', function()
613      eq_paths(
614        test_source_path,
615        exec_lua([[return vim.fs.root(..., 'CMakePresets.json')]], vim.fs.basename(nvim_prog))
616      )
617    end)
618
619    it('returns CWD (absolute path) for unnamed buffers', function()
620      assert(n.fn.isabsolutepath(test_source_path) == 1)
621      command('new')
622      eq_paths(test_source_path, exec_lua([[return vim.fs.root(0, 'CMakePresets.json')]]))
623    end)
624
625    it("returns CWD (absolute path) for buffers with non-empty 'buftype'", function()
626      assert(n.fn.isabsolutepath(test_source_path) == 1)
627      command('new')
628      command('set buftype=nofile')
629      command('file lua://')
630      eq_paths(test_source_path, exec_lua([[return vim.fs.root(0, 'CMakePresets.json')]]))
631    end)
632
633    it('returns CWD (absolute path) if no match is found', function()
634      assert(n.fn.isabsolutepath(test_source_path) == 1)
635      eq_paths(
636        test_source_path,
637        exec_lua([[return vim.fs.root('file://bogus', 'CMakePresets.json')]])
638      )
639    end)
640  end)
641
642  describe('joinpath()', function()
643    it('works', function()
644      eq('foo/bar/baz', vim.fs.joinpath('foo', 'bar', 'baz'))
645      eq('foo/bar/baz', vim.fs.joinpath('foo', '/bar/', '/baz'))
646    end)
647    it('rewrites backslashes on Windows', function()
648      if is_os('win') then
649        eq('foo/bar/baz/zub/', vim.fs.joinpath([[foo]], [[\\bar\\\\baz]], [[zub\]]))
650      else
651        eq([[foo/\\bar\\\\baz/zub\]], vim.fs.joinpath([[foo]], [[\\bar\\\\baz]], [[zub\]]))
652      end
653    end)
654    it('strips redundant slashes', function()
655      if is_os('win') then
656        eq('foo/bar/baz/zub/', vim.fs.joinpath([[foo//]], [[\\bar\\\\baz]], [[zub\]]))
657      else
658        eq('foo/bar/baz/zub/', vim.fs.joinpath([[foo]], [[//bar////baz]], [[zub/]]))
659      end
660    end)
661    it('handles empty segments', function()
662      eq('foo/bar', vim.fs.joinpath('', 'foo', '', 'bar', ''))
663      eq('foo/bar', vim.fs.joinpath('', '', 'foo', 'bar', '', ''))
664      eq('', vim.fs.joinpath(''))
665      eq('', vim.fs.joinpath('', '', '', ''))
666    end)
667  end)
668
669  describe('slug()', function()
670    it('replaces unsafe characters with "-"', function()
671      -- `\` is normalized to `/` on Windows, so the hash differs per platform
672      eq(
673        'a-b-c-d-e-f-g-h-i-j-k-l-'
674          .. vim.fn.sha256(vim.fs.normalize('a/b\\c:d*e?f"g<h>i|j k\tl')):sub(1, 8),
675        vim.fs.slug('a/b\\c:d*e?f"g<h>i|j k\tl')
676      )
677      eq('a-16b8a9f5', vim.fs.slug('a/ '))
678      eq('a-ca978112', vim.fs.slug('a/.'))
679    end)
680
681    it('works', function()
682      -- `=special`
683      eq('=special-8a5edab2', vim.fs.slug('/'))
684      eq('=special-ab5df625', vim.fs.slug('...'))
685      eq('=special-11d925ec', vim.fs.slug('-------'))
686      eq('src-foo-init.lua-cf05d2fe', vim.fs.slug('/src/foo/init.lua'))
687      eq('C--src-project-main.c-3b0eb5f5', vim.fs.slug('C:/src/project/main.c'))
688      eq('con.txt-d3bde286', vim.fs.slug('con.txt'))
689      -- Windows reserved names.
690      eq('con-1143da2b', vim.fs.slug('con'))
691      eq('com¹-bdcbdc69', vim.fs.slug('com¹'))
692      eq('NUL-ae6de182', vim.fs.slug('NUL'))
693      eq('Prn-0d399452', vim.fs.slug('Prn'))
694      eq('aux-321f6814', vim.fs.slug('aux'))
695      eq('con.foo.bar-f386c405', vim.fs.slug('con.foo.bar'))
696      eq('con-.-txt-48f98581', vim.fs.slug('con . txt'))
697      -- URIs are prefixed with `=uri-<scheme>-`.
698      eq('=uri-term-foo-bar-123-bash-7fd6bb99', vim.fs.slug('term://foo/bar//123:bash'))
699      eq('=uri-http-example.com-2e152ec0', vim.fs.slug('http://example.com'))
700      eq('=uri-scp-host-path-5188b9a2', vim.fs.slug('scp://host/path'))
701      -- $HOME is replaced with `~`
702      local p = vim.uv.os_homedir() .. '/my-project'
703      local hash8_2 = vim.fn.sha256(vim.fs.normalize(p)):sub(1, 8)
704      eq('~-my-project-' .. hash8_2, vim.fs.slug(p))
705
706      -- Windows-only cases.
707      if is_os('win') then
708        eq('=unc-foo-dir-file-549fb6e7', vim.fs.slug([[\\foo\dir\file]]))
709        -- `\\?\` and `\\.\`
710        eq(
711          '---Volume{a1b2c3d4-aa00-4000-a111-1a2b3c4d5e6f}-dir-file-cfda6a98',
712          vim.fs.slug([[\\?\Volume{a1b2c3d4-aa00-4000-a111-1a2b3c4d5e6f}\dir\file]])
713        )
714        eq('---C--dir-file-e8f30888', vim.fs.slug([[\\?\C:\dir\file]]))
715        eq('-.-COM1-e0e5710d', vim.fs.slug([[\\.\COM1]]))
716      end
717    end)
718
719    it('`opts.maxlen`', function()
720      -- maxlen < 8 is an error
721      t.matches('`opts.maxlen` must be >= 8', t.pcall_err(vim.fs.slug, 'foo', { maxlen = 7 }))
722
723      eq('2c26b46b', vim.fs.slug('foo', { maxlen = 8 }))
724      eq('2c26b46b', vim.fs.slug('foo', { maxlen = 11 }))
725      eq('foo-2c26b46b', vim.fs.slug('foo', { maxlen = 12 }))
726      eq('ddab29ff', vim.fs.slug('foo.txt', { maxlen = 12 }))
727      eq('foo-2c26b46b', vim.fs.slug('foo', { maxlen = 13 }))
728
729      -- truncates to "{head}~~~{tail}-{hash8}"
730      eq(
731        'aaaa-~~~-ffff-gggg-file.txt-7bd52057',
732        vim.fs.slug('/aaaa/bbbb/cccc/dddd/eeee/ffff/gggg/file.txt', { maxlen = 40 })
733      )
734      eq('测~~~-测试3-58cf4a70', vim.fs.slug('/测试1/测试测试2/测试3', { maxlen = 25 }))
735      eq('ab~~~uvwxyz-71c480df', vim.fs.slug('abcdefghijklmnopqrstuvwxyz', { maxlen = 20 }))
736      eq('dir~~~试.md-d4141f20', vim.fs.slug(('dir/'):rep(20) .. '测试.md', { maxlen = 22 }))
737      eq('~~~试abc-ab138cd6', vim.fs.slug('测试abc测试abc', { maxlen = 18 }))
738      eq('~~~d-473a1da7', vim.fs.slug('foo/bar/longlonglong.md', { maxlen = 13 }))
739      eq('f~~~md-473a1da7', vim.fs.slug('foo/bar/longlonglong.md', { maxlen = 15 }))
740    end)
741  end)
742
743  describe('normalize()', function()
744    it('removes trailing /', function()
745      eq('/home/user', vim.fs.normalize('/home/user/'))
746    end)
747    it('works with /', function()
748      eq('/', vim.fs.normalize('/'))
749    end)
750    it('works with ~', function()
751      eq(vim.fs.normalize(assert(vim.uv.os_homedir())) .. '/src/foo', vim.fs.normalize('~/src/foo'))
752      eq('~/src/foo', vim.fs.normalize('~/src/foo', { plain = true }))
753    end)
754    it('works with environment variables', function()
755      local xdg_config_home = test_build_dir .. '/.config'
756      eq(
757        xdg_config_home .. '/nvim',
758        exec_lua(function()
759          return vim._with({ env = { XDG_CONFIG_HOME = xdg_config_home } }, function()
760            return vim.fs.normalize('$XDG_CONFIG_HOME/nvim')
761          end)
762        end)
763      )
764      eq('$XDG_CONFIG_HOME/nvim', vim.fs.normalize('$XDG_CONFIG_HOME/nvim', { plain = true }))
765    end)
766
767    -- Opts required for testing posix paths and win paths
768    local posix_opts = { win = false }
769    local win_opts = { win = true }
770
771    it('preserves leading double slashes in POSIX paths', function()
772      eq('//foo', vim.fs.normalize('//foo', posix_opts))
773      eq('//foo/bar', vim.fs.normalize('//foo//bar////', posix_opts))
774      eq('/foo', vim.fs.normalize('///foo', posix_opts))
775      eq('//', vim.fs.normalize('//', posix_opts))
776      eq('/', vim.fs.normalize('///', posix_opts))
777      eq('/foo/bar', vim.fs.normalize('/foo//bar////', posix_opts))
778    end)
779
780    it('normalizes drive letter', function()
781      eq('C:/', vim.fs.normalize('C:/', win_opts))
782      eq('C:/', vim.fs.normalize('c:/', win_opts))
783      eq('D:/', vim.fs.normalize('d:/', win_opts))
784      eq('C:', vim.fs.normalize('C:', win_opts))
785      eq('C:', vim.fs.normalize('c:', win_opts))
786      eq('D:', vim.fs.normalize('d:', win_opts))
787      eq('C:/foo/test', vim.fs.normalize('C:/foo/test/', win_opts))
788      eq('C:/foo/test', vim.fs.normalize('c:/foo/test/', win_opts))
789      eq('D:foo/test', vim.fs.normalize('D:foo/test/', win_opts))
790      eq('D:foo/test', vim.fs.normalize('d:foo/test/', win_opts))
791    end)
792
793    it('always treats paths as case-sensitive #31833', function()
794      eq('TEST', vim.fs.normalize('TEST', win_opts))
795      eq('test', vim.fs.normalize('test', win_opts))
796      eq('C:/FOO/test', vim.fs.normalize('C:/FOO/test', win_opts))
797      eq('C:/foo/test', vim.fs.normalize('C:/foo/test', win_opts))
798      eq('//SERVER/SHARE/FOO/BAR', vim.fs.normalize('//SERVER/SHARE/FOO/BAR', win_opts))
799      eq('//server/share/foo/bar', vim.fs.normalize('//server/share/foo/bar', win_opts))
800      eq('C:/FOO/test', vim.fs.normalize('c:/FOO/test', win_opts))
801    end)
802
803    it('allows backslashes on unix-based os', function()
804      eq('/home/user/hello\\world', vim.fs.normalize('/home/user/hello\\world', posix_opts))
805    end)
806
807    it('preserves / after drive letters', function()
808      eq('C:/', vim.fs.normalize([[C:\]], win_opts))
809    end)
810
811    it('works with UNC and DOS device paths', function()
812      eq('//server/share/foo/bar', vim.fs.normalize([[\\server\\share\\\foo\bar\\\]], win_opts))
813      eq('//system07/C$/', vim.fs.normalize([[\\system07\C$\\\\]], win_opts))
814      eq('//./C:/foo/bar', vim.fs.normalize([[\\.\\C:\foo\\\\bar]], win_opts))
815      eq('//?/C:/foo/bar', vim.fs.normalize([[\\?\C:\\\foo\bar\\\\]], win_opts))
816      eq(
817        '//?/UNC/server/share/foo/bar',
818        vim.fs.normalize([[\\?\UNC\server\\\share\\\\foo\\\bar]], win_opts)
819      )
820      eq('//./BootPartition/foo/bar', vim.fs.normalize([[\\.\BootPartition\\foo\bar]], win_opts))
821      eq(
822        '//./Volume{12345678-1234-1234-1234-1234567890AB}/foo/bar',
823        vim.fs.normalize([[\\.\Volume{12345678-1234-1234-1234-1234567890AB}\\\foo\bar\\]], win_opts)
824      )
825    end)
826
827    it('handles invalid UNC and DOS device paths', function()
828      eq('//server/share', vim.fs.normalize([[\\server\share]], win_opts))
829      eq('//server/', vim.fs.normalize([[\\server\]], win_opts))
830      eq('//./UNC/server/share', vim.fs.normalize([[\\.\UNC\server\share]], win_opts))
831      eq('//?/UNC/server/', vim.fs.normalize([[\\?\UNC\server\]], win_opts))
832      eq('//?/UNC/server/..', vim.fs.normalize([[\\?\UNC\server\..]], win_opts))
833      eq('//./', vim.fs.normalize([[\\.\]], win_opts))
834      eq('//./foo', vim.fs.normalize([[\\.\foo]], win_opts))
835      eq('//./BootPartition', vim.fs.normalize([[\\.\BootPartition]], win_opts))
836    end)
837
838    it('converts backward slashes', function()
839      eq('C:/Users/jdoe', vim.fs.normalize([[C:\Users\jdoe]], win_opts))
840    end)
841
842    describe('. and .. component resolving', function()
843      it('works', function()
844        -- Windows paths
845        eq('C:/Users', vim.fs.normalize([[C:\Users\jdoe\Downloads\.\..\..\]], win_opts))
846        eq('C:/Users/jdoe', vim.fs.normalize([[C:\Users\jdoe\Downloads\.\..\.\.\]], win_opts))
847        eq('C:/', vim.fs.normalize('C:/Users/jdoe/Downloads/./../../../', win_opts))
848        eq('C:foo', vim.fs.normalize([[C:foo\bar\.\..\.]], win_opts))
849        -- POSIX paths
850        eq('/home', vim.fs.normalize('/home/jdoe/Downloads/./../..', posix_opts))
851        eq('/home/jdoe', vim.fs.normalize('/home/jdoe/Downloads/./../././', posix_opts))
852        eq('/', vim.fs.normalize('/home/jdoe/Downloads/./../../../', posix_opts))
853        -- OS-agnostic relative paths
854        eq('foo/bar/baz', vim.fs.normalize('foo/bar/foobar/../baz/./'))
855        eq('foo/bar', vim.fs.normalize('foo/bar/foobar/../baz/./../../bar/./.'))
856      end)
857
858      it('works when relative path reaches current directory', function()
859        eq('C:', vim.fs.normalize('C:foo/bar/../../.', win_opts))
860
861        eq('.', vim.fs.normalize('.'))
862        eq('.', vim.fs.normalize('././././'))
863        eq('.', vim.fs.normalize('foo/bar/../../.'))
864      end)
865
866      it('works when relative path goes outside current directory', function()
867        eq('../../foo/bar', vim.fs.normalize('../../foo/bar'))
868        eq('../foo', vim.fs.normalize('foo/bar/../../../foo'))
869
870        eq('C:../foo', vim.fs.normalize('C:../foo', win_opts))
871        eq('C:../../foo/bar', vim.fs.normalize('C:foo/../../../foo/bar', win_opts))
872      end)
873
874      it('.. in root directory resolves to itself', function()
875        eq('C:/', vim.fs.normalize('C:/../../', win_opts))
876        eq('C:/foo', vim.fs.normalize('C:/foo/../../foo', win_opts))
877
878        eq('//server/share/', vim.fs.normalize([[\\server\share\..\..]], win_opts))
879        eq('//server/share/foo', vim.fs.normalize([[\\server\\share\foo\..\..\foo]], win_opts))
880
881        eq('//./C:/', vim.fs.normalize([[\\.\C:\..\..]], win_opts))
882        eq('//?/C:/foo', vim.fs.normalize([[\\?\C:\..\..\foo]], win_opts))
883
884        eq('//./UNC/server/share/', vim.fs.normalize([[\\.\UNC\\server\share\..\..\]], win_opts))
885        eq(
886          '//?/UNC/server/share/foo',
887          vim.fs.normalize([[\\?\UNC\server\\share\..\..\foo]], win_opts)
888        )
889
890        eq('//?/BootPartition/', vim.fs.normalize([[\\?\BootPartition\..\..]], win_opts))
891        eq('//./BootPartition/foo', vim.fs.normalize([[\\.\BootPartition\..\..\foo]], win_opts))
892
893        eq('/', vim.fs.normalize('/../../', posix_opts))
894        eq('/foo', vim.fs.normalize('/foo/../../foo', posix_opts))
895      end)
896    end)
897  end)
898
899  describe('abspath()', function()
900    local cwd = assert(t.fix_slashes(assert(vim.uv.cwd())))
901    local home = t.fix_slashes(assert(vim.uv.os_homedir()))
902
903    it('expands relative paths', function()
904      assert(n.fn.isabsolutepath(cwd) == 1)
905      eq(cwd, vim.fs.abspath('.'))
906      eq(cwd .. '/foo', vim.fs.abspath('foo'))
907      eq(cwd .. '/././foo', vim.fs.abspath('././foo'))
908      eq(cwd .. '/.././../foo', vim.fs.abspath('.././../foo'))
909    end)
910
911    it('works with absolute paths', function()
912      if is_os('win') then
913        eq([[C:/foo]], vim.fs.abspath([[C:\foo]]))
914        eq([[C:/foo/../.]], vim.fs.abspath([[C:\foo\..\.]]))
915        eq('//foo/bar', vim.fs.abspath('\\\\foo\\bar'))
916        eq('//foo/bar', vim.fs.abspath('\\\\foo\\bar'))
917      else
918        eq('/foo/../.', vim.fs.abspath('/foo/../.'))
919        eq('/foo/bar', vim.fs.abspath('/foo/bar'))
920      end
921    end)
922
923    it('with `cwd`', function()
924      local parent_cwd = vim.fs.dirname(cwd)
925      eq(parent_cwd, vim.fs.abspath('.', { cwd = parent_cwd }))
926      eq(parent_cwd .. '/foo', vim.fs.abspath('foo', { cwd = parent_cwd }))
927      eq(parent_cwd .. '/.././../foo', vim.fs.abspath('.././../foo', { cwd = parent_cwd }))
928      eq('/foo/bar', vim.fs.abspath('/foo/bar', { cwd = parent_cwd }))
929    end)
930
931    it('expands ~', function()
932      eq(home .. '/foo', vim.fs.abspath('~/foo'))
933      eq(home .. '/./.././foo', vim.fs.abspath('~/./.././foo'))
934    end)
935
936    it('does not expand ~ if plain=true', function()
937      eq(cwd .. '/~/foo', vim.fs.abspath('~/foo', { plain = true }))
938      eq(cwd .. '/~/./.././foo', vim.fs.abspath('~/./.././foo', { plain = true }))
939    end)
940
941    if is_os('win') then
942      it('works with drive-specific cwd on Windows', function()
943        local cwd_drive = cwd:match('^%w:')
944
945        eq(cwd .. '/foo', vim.fs.abspath(cwd_drive .. 'foo'))
946      end)
947    end
948  end)
949
950  describe('relpath()', function()
951    it('works', function()
952      local cwd = assert(t.fix_slashes(assert(vim.uv.cwd())))
953      local my_dir = vim.fs.joinpath(cwd, 'foo')
954
955      eq(nil, vim.fs.relpath('/var/lib', '/var'))
956      eq(nil, vim.fs.relpath('/var/lib', '/bin'))
957      eq(nil, vim.fs.relpath(my_dir, 'bin'))
958      eq(nil, vim.fs.relpath(my_dir, './bin'))
959      eq(nil, vim.fs.relpath(my_dir, '././'))
960      eq(nil, vim.fs.relpath(my_dir, '../'))
961      eq(nil, vim.fs.relpath('/var/lib', '/'))
962      eq(nil, vim.fs.relpath('/var/lib', '//'))
963      eq(nil, vim.fs.relpath(' ', '/var'))
964      eq(nil, vim.fs.relpath(' ', '/var'))
965      eq('.', vim.fs.relpath('/var/lib', '/var/lib'))
966      eq('lib', vim.fs.relpath('/var/', '/var/lib'))
967      eq('var/lib', vim.fs.relpath('/', '/var/lib'))
968      eq('bar/package.json', vim.fs.relpath('/foo/test', '/foo/test/bar/package.json'))
969      eq('foo/bar', vim.fs.relpath(cwd, 'foo/bar'))
970      eq('foo/bar', vim.fs.relpath('.', vim.fs.joinpath(cwd, 'foo/bar')))
971      eq('bar', vim.fs.relpath('foo', 'foo/bar'))
972      eq(nil, vim.fs.relpath('/var/lib', '/var/library/foo'))
973
974      if is_os('win') then
975        eq(nil, vim.fs.relpath('/', ' '))
976        eq(nil, vim.fs.relpath('/', 'var'))
977      else
978        local cwd_rel_root = cwd:sub(2)
979        eq(cwd_rel_root .. '/ ', vim.fs.relpath('/', ' '))
980        eq(cwd_rel_root .. '/var', vim.fs.relpath('/', 'var'))
981      end
982
983      if is_os('win') then
984        eq(nil, vim.fs.relpath('c:/aaaa/', '/aaaa/cccc'))
985        eq(nil, vim.fs.relpath('c:/aaaa/', './aaaa/cccc'))
986        eq(nil, vim.fs.relpath('c:/aaaa/', 'aaaa/cccc'))
987        eq(nil, vim.fs.relpath('c:/blah\\blah', 'd:/games'))
988        eq(nil, vim.fs.relpath('c:/games', 'd:/games'))
989        eq(nil, vim.fs.relpath('c:/games', 'd:/games/foo'))
990        eq(nil, vim.fs.relpath('c:/aaaa/bbbb', 'c:/aaaa'))
991        eq('cccc', vim.fs.relpath('c:/aaaa/', 'c:/aaaa/cccc'))
992        eq('aaaa/bbbb', vim.fs.relpath('C:/', 'c:\\aaaa\\bbbb'))
993        eq('bar/package.json', vim.fs.relpath('C:\\foo\\test', 'C:\\foo\\test\\bar\\package.json'))
994        eq('baz', vim.fs.relpath('\\\\foo\\bar', '\\\\foo\\bar\\baz'))
995        eq(nil, vim.fs.relpath('a/b/c', 'a\\b'))
996        eq('d', vim.fs.relpath('a/b/c', 'a\\b\\c\\d'))
997        eq('.', vim.fs.relpath('\\\\foo\\bar\\baz', '\\\\foo\\bar\\baz'))
998        eq(nil, vim.fs.relpath('C:\\foo\\test', 'C:\\foo\\Test\\bar\\package.json'))
999      end
1000    end)
1001  end)
1002
1003  describe('rm()', function()
1004    before_each(function()
1005      t.mkdir('Xtest_fs-rm')
1006      t.write_file('Xtest_fs-rm/file-to-link', 'File to link')
1007      t.mkdir('Xtest_fs-rm/dir-to-link')
1008      t.write_file('Xtest_fs-rm/dir-to-link/file', 'File in dir to link')
1009    end)
1010
1011    after_each(function()
1012      vim.uv.fs_unlink('Xtest_fs-rm/dir-to-link/file')
1013      vim.uv.fs_rmdir('Xtest_fs-rm/dir-to-link')
1014      vim.uv.fs_unlink('Xtest_fs-rm/file-to-link')
1015      vim.uv.fs_rmdir('Xtest_fs-rm')
1016    end)
1017
1018    it('symlink', function()
1019      -- File
1020      vim.uv.fs_symlink('Xtest_fs-rm/file-to-link', 'Xtest_fs-rm/file-as-link')
1021      vim.fs.rm('Xtest_fs-rm/file-as-link')
1022      eq(nil, vim.uv.fs_stat('Xtest_fs-rm/file-as-link'))
1023      eq({ 'File to link' }, fn.readfile('Xtest_fs-rm/file-to-link'))
1024
1025      -- Directory
1026      local function assert_rm_symlinked_dir(opts)
1027        vim.uv.fs_symlink('Xtest_fs-rm/dir-to-link', 'Xtest_fs-rm/dir-as-link')
1028        vim.fs.rm('Xtest_fs-rm/dir-as-link', opts)
1029        eq(nil, vim.uv.fs_stat('Xtest_fs-rm/dir-as-link'))
1030        eq({ 'File in dir to link' }, fn.readfile('Xtest_fs-rm/dir-to-link/file'))
1031      end
1032
1033      assert_rm_symlinked_dir({})
1034      assert_rm_symlinked_dir({ force = true })
1035      assert_rm_symlinked_dir({ recursive = true })
1036      assert_rm_symlinked_dir({ recursive = true, force = true })
1037    end)
1038  end)
1039
1040  describe('ext()', function()
1041    it('works', function()
1042      -- See test/functional/vimscript/fnamemodify_spec.lua
1043    end)
1044  end)
1045end)