robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
14.9 KiB459 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, before_each = t.describe, t.it, t.before_each
5local eq = t.eq
6local exec_lua = n.exec_lua
7local clear = n.clear
8local is_ci = t.is_ci
9local is_os = t.is_os
10local skip = t.skip
11
12-- Create a file via a rename to avoid multiple
13-- events which can happen with some backends on some platforms
14local function touch(path)
15  local tmp = t.tmpname()
16  assert(vim.uv.fs_rename(tmp, path))
17end
18
19describe('vim._watch', function()
20  before_each(function()
21    clear()
22  end)
23
24  it('watchdirs() does not scan excluded subtrees', function()
25    local root_dir = t.tmpname(false)
26    t.finally(function()
27      n.rmdir(root_dir)
28    end)
29    n.mkdir_p(root_dir .. '/src/deep')
30    n.mkdir_p(root_dir .. '/node_modules/pkg/excluded/deep')
31
32    -- Also cover a pattern that matches the directory but not its descendants.
33    for _, pattern in ipairs({ '**/node_modules/*/**', '**/excluded' }) do
34      local scanned = exec_lua(function(root, exclude_pattern)
35        root = vim.fs.normalize(root)
36        local scanned = {}
37        local fs_scandir = vim.uv.fs_scandir
38        vim.uv.fs_scandir = function(path, ...)
39          scanned[#scanned + 1] = path:sub(#root + 1)
40          return fs_scandir(path, ...)
41        end
42        local cancel = vim._watch.watchdirs(root, {
43          exclude_pattern = vim.glob.to_lpeg(exclude_pattern),
44        }, function() end)
45        vim.uv.fs_scandir = fs_scandir
46        cancel()
47        table.sort(scanned)
48        return scanned
49      end, root_dir, pattern)
50
51      eq({ '', '/node_modules', '/node_modules/pkg', '/src', '/src/deep' }, scanned, pattern)
52    end
53  end)
54
55  it('watchdirs() tolerates directories deleted during setup', function()
56    local root_dir = t.tmpname(false)
57    t.finally(function()
58      n.rmdir(root_dir)
59    end)
60    n.mkdir_p(root_dir .. '/gone')
61
62    exec_lua(function(root)
63      local dir = vim.fs.dir
64      vim.fs.dir = function(path, opts)
65        local iter = dir(path, opts)
66        return function()
67          local name, kind = iter()
68          if name == 'gone' then
69            -- Delete after enumeration, before the backend starts watching it.
70            assert(vim.uv.fs_rmdir(root .. '/gone'))
71          end
72          return name, kind
73        end
74      end
75      local cancel = vim._watch.watchdirs(root, { on_error = error }, function() end)
76      vim.fs.dir = dir
77      cancel()
78    end, root_dir)
79  end)
80
81  it('inotify() reports failure to start the process', function()
82    exec_lua(function()
83      vim.env.PATH = ''
84      local errors = {}
85      local cancel = vim._watch.inotify('.', {
86        on_error = function(err)
87          errors[#errors + 1] = err
88        end,
89      }, function() end)
90      assert(vim._watch.active().inotify == 0)
91      cancel()
92      assert(#errors == 1, vim.inspect(errors))
93      assert(errors[1]:find('ENOENT', 1, true), errors[1])
94    end)
95  end)
96
97  it('releases earlier subscriptions when setup raises', function()
98    exec_lua(function()
99      local starts, stops = 0, 0
100      vim.system = function()
101        starts = starts + 1
102        if starts == 2 then
103          error('cannot start watcher')
104        end
105        return {
106          kill = function()
107            stops = stops + 1
108          end,
109        }
110      end
111
112      local ok, err = pcall(vim._watch.inotify, {
113        { path = '/one' },
114        { path = '/two' },
115      }, { on_error = error }, function() end)
116
117      assert(not ok and err:find('cannot start watcher', 1, true))
118      assert(starts == 2 and stops == 1, 'started watchers must be stopped on error')
119      assert(vim._watch.active().inotify == 0)
120    end)
121  end)
122
123  it('inotify() groups rules by root and filters file events', function()
124    local events = exec_lua(function()
125      local outputs = {}
126      vim.system = function(cmd, opts)
127        local root = cmd[#cmd]
128        assert(not outputs[root], 'rules for one root must share a watcher')
129        outputs[root] = opts.stdout
130        return {
131          kill = function()
132            outputs[root] = nil
133          end,
134        }
135      end
136
137      local watch = vim._watch
138      local T = watch.FileChangeType
139      local python = '/one/*.py'
140      local events = {}
141      local cancel = watch.inotify({
142        { path = '/one', pattern = python, events = { T.Changed } },
143        { path = '/one', pattern = python, events = { T.Created, T.Changed } },
144        { path = '/one', pattern = '**/*.txt' },
145        { path = '/two' },
146      }, {
147        include_pattern = '**/*.py',
148        exclude_pattern = '**/ignored.py',
149        on_error = error,
150      }, function(path, change_type)
151        events[#events + 1] = { path, change_type }
152      end)
153      assert(watch.active().inotify == 2)
154
155      outputs['/one'](nil, '/one/ MODIFY file.py\n') -- Matches two rules, reported once.
156      outputs['/one'](nil, '/one/ CREATE file.py\n')
157      outputs['/one'](nil, '/one/ DELETE file.py\n') -- Wrong event type.
158      outputs['/one'](nil, '/one/ MODIFY file.txt\n') -- Global include still applies.
159      outputs['/one'](nil, '/one/ MODIFY ignored.py\n')
160      outputs['/two'](nil, '/two/ DELETE file.py\n') -- No per-rule filters.
161      cancel()
162      cancel()
163      assert(not next(outputs))
164      assert(watch.active().inotify == 0)
165      return events
166    end)
167    eq({ { '/one/file.py', 2 }, { '/one/file.py', 1 }, { '/two/file.py', 3 } }, events)
168  end)
169
170  it('inotify() shares glob watches and releases subscriptions independently', function()
171    exec_lua(function()
172      local root = vim.fs.normalize(assert(vim.uv.cwd()))
173      local prefix = vim.fn.escape(root, '\\/*?[]{}#') .. '/'
174      local processes = {}
175      vim.system = function(_, opts)
176        processes[#processes + 1] = opts
177        return {
178          kill = function()
179            assert(not opts.stopped, 'process stopped twice')
180            opts.stopped = true
181          end,
182        }
183      end
184      local changes, errors = { 0, 0, 0, 0 }, { 0, 0, 0, 0 }
185      local function subscribe(id, pattern)
186        local path = id == 1 and root or { { path = root .. '/' } }
187        return vim._watch.inotify(path, {
188          include_pattern = { prefix .. (pattern or '*.{py,lua}') },
189          exclude_pattern = { '**/ignored.py' },
190          on_error = function()
191            errors[id] = errors[id] + 1
192          end,
193        }, function()
194          changes[id] = changes[id] + 1
195        end)
196      end
197      local cancel_a = subscribe(1)
198      local cancel_b = subscribe(2)
199      assert(#processes == 1, 'equivalent globs must share a backend')
200      assert(vim._watch.active().inotify == 1)
201      processes[1].stdout(nil, root .. '/ CREATE file.py')
202      assert(vim.deep_equal(changes, { 1, 1, 0, 0 }))
203      cancel_a()
204      cancel_a()
205      assert(not processes[1].stopped)
206      processes[1].stdout(nil, root .. '/ MODIFY file.py')
207      assert(vim.deep_equal(changes, { 1, 2, 0, 0 }))
208
209      processes[1].stderr(nil, 'watcher failed')
210      assert(vim.deep_equal(errors, { 0, 1, 0, 0 }))
211      assert(vim._watch.active().inotify == 1, 'backend remains owned after an error')
212      local cancel_c = subscribe(3)
213      assert(#processes == 2, 'failed backend must not be reused')
214      local cancel_d = subscribe(4, '*.txt')
215      assert(#processes == 3, 'different filters must not share a backend')
216      processes[2].stdout(nil, root .. '/ CREATE file.py')
217      processes[3].stdout(nil, root .. '/ CREATE file.py')
218      processes[3].stdout(nil, root .. '/ CREATE file.txt')
219      assert(vim.deep_equal(changes, { 1, 2, 1, 1 }))
220      cancel_b()
221      assert(processes[1].stopped and not processes[2].stopped)
222      cancel_c()
223      cancel_d()
224      assert(processes[2].stopped and processes[3].stopped)
225      assert(vim._watch.active().inotify == 0)
226    end)
227  end)
228
229  it('inotify() skips invalid globs without disabling sharing', function()
230    exec_lua(function()
231      local root = assert(vim.uv.cwd())
232      local outputs = {}
233      vim.system = function(_, opts)
234        outputs[#outputs + 1] = opts.stdout
235        return { kill = function() end }
236      end
237
238      local changes, errors, cancels = 0, {}, {}
239      for i = 1, 2 do
240        errors[i] = {}
241        cancels[i] = vim._watch.inotify({
242          { path = root, pattern = 'a/**b' },
243          { path = root, pattern = { '{foo}', '**/*.lua' } },
244        }, {
245          on_error = function(err)
246            errors[i][#errors[i] + 1] = err
247          end,
248        }, function()
249          changes = changes + 1
250        end)
251      end
252
253      assert(#errors[1] == 2 and #errors[2] == 2, 'each subscriber receives its own glob errors')
254      assert(#outputs == 1, 'valid rules still share a backend')
255      outputs[1](nil, root .. '/ MODIFY file.lua\n')
256      assert(changes == 2)
257      cancels[1]()
258      cancels[2]()
259      assert(vim._watch.active().inotify == 0)
260    end)
261  end)
262
263  it('watchdirs() keeps directories watched when only their files match a glob', function()
264    local root_dir = t.tmpname(false)
265    n.mkdir_p(root_dir .. '/src')
266    t.finally(function()
267      n.rmdir(root_dir)
268    end)
269    exec_lua(function(root)
270      root = vim.fs.normalize(root)
271      local callbacks = {}
272      vim.uv.new_fs_event = function()
273        return {
274          start = function(_, path, _, callback)
275            callbacks[path] = callback
276          end,
277          is_closing = function()
278            return false
279          end,
280          close = function() end,
281        }
282      end
283      local events = {}
284      local cancel = vim._watch.watchdirs(root, {
285        include_pattern = '**/*.py',
286        debounce = 1,
287      }, function(path)
288        events[#events + 1] = path
289      end)
290      assert(callbacks[root .. '/src'], 'existing parent directory must be watched')
291      vim.fn.mkdir(root .. '/new')
292      callbacks[root](nil, 'new', { rename = true })
293      assert(
294        vim.wait(1000, function()
295          return callbacks[root .. '/new'] ~= nil
296        end),
297        'new parent directory must be watched'
298      )
299      vim.fn.writefile({}, root .. '/new/file.py')
300      callbacks[root .. '/new'](nil, 'file.py', { rename = true })
301      assert(vim.wait(1000, function()
302        return #events == 1
303      end))
304      assert(events[1] == root .. '/new/file.py')
305      cancel()
306    end, root_dir)
307  end)
308
309  local function run(watchfunc)
310    local function do_watch(root_dir, watchfunc_)
311      exec_lua(
312        [[
313          local root_dir, watchfunc = ...
314
315          _G.events = {}
316
317          _G.stop_watch = vim._watch[watchfunc](root_dir, {
318            debounce = 100,
319            include_pattern = vim.lpeg.P(root_dir) * vim.lpeg.P("/file") ^ -1,
320            exclude_pattern = vim.lpeg.P(root_dir .. '/file.unwatched'),
321          }, function(path, change_type)
322            table.insert(_G.events, { path = path, change_type = change_type })
323          end)
324      ]],
325        root_dir,
326        watchfunc_
327      )
328    end
329
330    it(watchfunc .. '() reports nonexistent paths to on_error', function()
331      if watchfunc == 'inotify' then
332        skip(n.fn.executable('inotifywait') == 0, 'inotifywait not found')
333        skip(is_os('bsd'), 'inotifywait on bsd CI seems to expect path to exist?')
334        skip(t.is_arch('s390x'), 'inotifywait not available on s390x CI')
335      end
336
337      exec_lua(function(backend)
338        local errors = {}
339        local cancel = vim._watch[backend]('/i am /very/funny.go', {
340          on_error = function(err)
341            errors[#errors + 1] = err
342          end,
343        }, function()
344          error('Unexpected file change')
345        end)
346        assert(vim.wait(2000, function()
347          return #errors > 0
348        end))
349        if backend ~= 'inotify' then
350          assert(errors[1]:match('^ENOENT:'), errors[1])
351        end
352        assert(errors[1]:find('(watching /i am /very/funny.go)', 1, true), errors[1])
353        cancel()
354      end, watchfunc)
355    end)
356
357    if watchfunc ~= 'inotify' then
358      it(watchfunc .. '() logs startup failures without on_error', function()
359        local logfile = exec_lua(function(backend)
360          local logfile = vim.fs.joinpath(vim.fn.stdpath('log'), 'nvim-watch.log')
361          vim.fn.writefile({}, logfile)
362          local cancel = vim._watch[backend]('/i am /very/funny.go', {}, function()
363            error('Unexpected file change')
364          end)
365          assert(vim._watch.active()[backend] == 0)
366          cancel()
367          return logfile
368        end, watchfunc)
369        t.assert_log('%[ERROR%].-ENOENT:', logfile)
370      end)
371    end
372
373    it(watchfunc .. '() detects file changes', function()
374      if watchfunc == 'inotify' then
375        skip(is_os('win'), 'N/A: inotify not supported on Windows')
376        skip(is_os('mac'), 'flaky test on mac')
377        skip(not is_ci() and n.fn.executable('inotifywait') == 0, 'inotifywait not found')
378        skip(t.is_arch('s390x'), 'inotifywait not available on s390x CI')
379      end
380
381      -- Note: because this is not `elseif`, BSD is skipped for *all* cases...?
382      if watchfunc == 'watch' then
383        skip(is_os('mac'), 'flaky test on mac')
384        skip(is_os('bsd'), 'Stopped working on bsd after 3ca967387c49c754561c3b11a574797504d40f38')
385      elseif watchfunc == 'watchdirs' and is_os('mac') then
386        skip(true, 'weird failure since macOS 14 CI, see bbf208784ca279178ba0075b60d3e9c80f11da7a')
387      else
388        skip(
389          is_os('bsd'),
390          'kqueue only reports events on watched folder itself, not contained files #26110'
391        )
392      end
393
394      local expected_events = 0
395      --- Waits for a new event, or fails if no events are triggered.
396      local function wait_for_event()
397        expected_events = expected_events + 1
398        exec_lua(
399          [[
400            local expected_events = ...
401            assert(
402              vim.wait(3000, function()
403                return #_G.events == expected_events
404              end),
405              string.format(
406                'Timed out waiting for expected event no. %d. Current events seen so far: %s',
407                expected_events,
408                vim.inspect(events)
409              )
410            )
411        ]],
412          expected_events
413        )
414      end
415
416      local root_dir = vim.uv.fs_mkdtemp(vim.fs.dirname(t.tmpname(false)) .. '/nvim_XXXXXXXXXX')
417      local unwatched_path = root_dir .. '/file.unwatched'
418      local watched_path = root_dir .. '/file'
419
420      do_watch(root_dir, watchfunc)
421
422      if watchfunc ~= 'watch' then
423        vim.uv.sleep(200)
424      end
425
426      touch(watched_path)
427      touch(unwatched_path)
428      wait_for_event()
429
430      os.remove(watched_path)
431      os.remove(unwatched_path)
432      wait_for_event()
433
434      exec_lua [[_G.stop_watch()]]
435      -- No events should come through anymore
436
437      vim.uv.sleep(100)
438      touch(watched_path)
439      vim.uv.sleep(100)
440      os.remove(watched_path)
441      vim.uv.sleep(100)
442
443      eq({
444        {
445          change_type = exec_lua([[return vim._watch.FileChangeType.Created]]),
446          path = root_dir .. '/file',
447        },
448        {
449          change_type = exec_lua([[return vim._watch.FileChangeType.Deleted]]),
450          path = root_dir .. '/file',
451        },
452      }, exec_lua [[return _G.events]])
453    end)
454  end
455
456  run('watch')
457  run('watchdirs')
458  run('inotify')
459end)