robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
20.3 KiB674 linesraw
1local uv = vim.uv
2local log = vim.log.new({ name = 'nvim-watch' })
3
4local M = {}
5
6--- @enum vim._watch.FileChangeType
7--- Types of events watchers will emit.
8M.FileChangeType = {
9  Created = 1,
10  Changed = 2,
11  Deleted = 3,
12}
13
14--- A glob string or compiled LPeg pattern. Strings match full paths using `/` separators.
15--- Glob syntax follows [vim.glob] (LSP 3.17).
16--- @alias vim._watch.Pattern string|vim.lpeg.Pattern
17
18--- A list matches if any of its patterns matches. An empty list matches nothing.
19--- @alias vim._watch.Filter vim._watch.Pattern|vim._watch.Pattern[]
20
21--- Option and rule tables must not be modified while watching.
22--- @class vim._watch.Opts
23---
24--- @field debounce? integer ms
25---
26--- Handles watcher failures and invalid globs, with root and pattern context in the message.
27--- Invalid globs are skipped. Defaults to logging at ERROR in nvim-watch.log.
28--- @field on_error? fun(err: string)
29---
30--- Only changes matching this filter are reported. Parent directories remain watched for matching
31--- descendants. See vim._watch.Pattern for glob syntax. When nil, matches any path.
32--- @field include_pattern? vim._watch.Filter
33---
34--- Changes matching this filter are not reported. With watchdirs(), excluding a subdirectory
35--- excludes its entire subtree. When nil, matches nothing.
36--- @field exclude_pattern? vim._watch.Filter
37
38--- @alias vim._watch.Callback fun(path: string, change_type: vim._watch.FileChangeType)
39
40--- @class vim._watch.watch.Opts : vim._watch.Opts
41--- @field uvflags? uv.fs_event_start.flags See |uv.fs_event_start()|.
42
43--- Rules sharing a root use one backend watcher. Each event is reported once per root if any
44--- rule matches, subject to the include_pattern and exclude_pattern options.
45--- @class vim._watch.Rule
46--- @field path string Root to watch.
47--- @field pattern? vim._watch.Filter Matches full paths; nil matches everything.
48--- @field events? vim._watch.FileChangeType[] Defaults to all event types.
49
50--- @class (private) vim._watch.BackendOpts : vim._watch.watch.Opts
51--- @field include_pattern? vim.lpeg.Pattern
52--- @field exclude_pattern? vim.lpeg.Pattern
53--- @field on_error fun(err: string)
54
55--- @alias vim._watch.Backend fun(path: string, opts: vim._watch.BackendOpts, callback: vim._watch.Callback): (fun())?
56
57--- @class (private) vim._watch.Subscriber
58--- @field callback vim._watch.Callback
59--- @field on_error fun(err: string)
60
61--- @class (private) vim._watch.Shared
62--- @field key table
63--- @field stat? uv.fs_stat.result
64--- @field failed boolean
65--- @field subscribers table<vim._watch.Subscriber, true>
66--- @field cancel? fun()
67
68--- @type table<'watch'|'watchdirs'|'inotify', table<string, table<vim._watch.Shared, true>>>
69local shared = { watch = {}, watchdirs = {}, inotify = {} }
70
71--- Counts backend watchers with outstanding subscriptions, excluding failed starts.
72--- @return {watch: integer, watchdirs: integer, inotify: integer}
73function M.active()
74  local active = { watch = 0, watchdirs = 0, inotify = 0 }
75
76  for name, paths in pairs(shared) do
77    for _, entries in pairs(paths) do
78      active[name] = active[name] + vim.tbl_count(entries)
79    end
80  end
81
82  return active
83end
84
85--- An omitted filter matches everything; invalid or empty filters return nil.
86--- @param filter vim._watch.Filter?
87--- @param on_error fun(err: string)
88--- @return vim.lpeg.Pattern?
89local function compile(filter, on_error)
90  if filter == nil then
91    return vim.lpeg.P(true)
92  elseif type(filter) == 'userdata' then
93    return filter --[[@as vim.lpeg.Pattern]]
94  elseif type(filter) == 'string' then
95    local ok, pattern = pcall(vim.glob.to_lpeg, filter)
96    if not ok then
97      on_error(('Invalid glob %q: %s'):format(filter, pattern))
98      return nil
99    end
100
101    return pattern
102  end
103
104  local pattern --- @type vim.lpeg.Pattern?
105
106  for _, item in ipairs(filter) do
107    local p = compile(item, on_error)
108    if p then
109      pattern = pattern and pattern + p or p
110    end
111  end
112
113  return pattern
114end
115
116--- @param entry vim._watch.Shared
117--- @param method 'callback'|'on_error'
118--- @param ... any
119local function emit(entry, method, ...)
120  local first_error
121
122  -- Callbacks can subscribe or cancel other subscriptions while handling an event.
123  for _, subscriber in ipairs(vim.tbl_keys(entry.subscribers)) do
124    if entry.subscribers[subscriber] then
125      -- EmmyLua rejects the union of callback signatures passed to pcall.
126      --- @diagnostic disable-next-line: param-type-mismatch
127      local ok, err = pcall(subscriber[method], ...)
128      if not ok then
129        first_error = first_error or tostring(err)
130      end
131    end
132  end
133
134  if first_error then
135    error(first_error)
136  end
137end
138
139--- @param name 'watch'|'watchdirs'|'inotify'
140--- @param backend vim._watch.Backend
141--- @param path string
142--- @param opts vim._watch.watch.Opts
143--- @param rules {pattern: vim._watch.Filter?, events: vim._watch.FileChangeType[]?}[]
144--- @param subscriber vim._watch.Subscriber
145--- @return fun()
146local function subscribe(name, backend, path, opts, rules, subscriber)
147  local key = {
148    include_pattern = opts.include_pattern,
149    exclude_pattern = opts.exclude_pattern,
150    debounce = name == 'watchdirs' and (opts.debounce or 500) or nil,
151    uvflags = name == 'watch' and (opts.uvflags or {}) or nil,
152    rules = rules,
153  }
154
155  -- Validate every subscription, even when reusing a backend. Invalid globs do not mean the
156  -- backend has failed, and each subscriber should receive its own diagnostics.
157  local include_pattern = compile(key.include_pattern, subscriber.on_error)
158  local exclude_pattern = key.exclude_pattern and compile(key.exclude_pattern, subscriber.on_error)
159  local compiled = {} --- @type {pattern: vim.lpeg.Pattern, events: vim._watch.FileChangeType[]?}[]
160  local include = vim.lpeg.P(false)
161
162  for _, rule in ipairs(key.rules) do
163    local pattern = compile(rule.pattern, subscriber.on_error)
164    if pattern then
165      compiled[#compiled + 1] = { pattern = pattern, events = rule.events }
166      include = include + pattern
167    end
168  end
169
170  if not include_pattern or #compiled == 0 then
171    return function() end
172  end
173
174  local stat = uv.fs_stat(path)
175  local entry --- @type vim._watch.Shared?
176
177  for r in pairs(shared[name][path] or {}) do
178    if
179      not r.failed
180      and stat
181      and r.stat
182      and stat.dev == r.stat.dev
183      and stat.ino == r.stat.ino
184      and vim.deep_equal(r.key, key)
185    then
186      entry = r
187      break
188    end
189  end
190
191  if entry then
192    entry.subscribers[subscriber] = true
193  else
194    entry = { key = key, stat = stat, failed = false, subscribers = { [subscriber] = true } }
195
196    --- @type vim._watch.BackendOpts
197    local backend_opts = {
198      debounce = key.debounce,
199      uvflags = key.uvflags,
200      -- Both filters must match from the beginning of the full path.
201      -- EmmyLua does not infer the LPeg length operator's result type.
202      ---@diagnostic disable-next-line: assign-type-mismatch
203      include_pattern = #include_pattern * include,
204      exclude_pattern = exclude_pattern,
205      on_error = function(err)
206        entry.failed = true
207        emit(entry, 'on_error', err)
208      end,
209    }
210
211    entry.cancel = backend(path, backend_opts, function(fullpath, change_type)
212      for _, rule in ipairs(compiled) do
213        if
214          rule.pattern:match(fullpath) ~= nil
215          and (not rule.events or vim.list_contains(rule.events, change_type))
216        then
217          emit(entry, 'callback', fullpath, change_type)
218          return
219        end
220      end
221    end)
222
223    if not entry.cancel then
224      return function() end
225    end
226
227    -- Publish only after setup completes, so reentrant calls cannot reuse partial watchers.
228    shared[name][path] = shared[name][path] or {}
229    shared[name][path][entry] = true
230  end
231
232  return function()
233    if not entry.subscribers[subscriber] then
234      return
235    end
236
237    entry.subscribers[subscriber] = nil
238
239    if not next(entry.subscribers) then
240      shared[name][path][entry] = nil
241      if not next(shared[name][path]) then
242        shared[name][path] = nil
243      end
244
245      assert(entry.cancel)()
246    end
247  end
248end
249
250--- Compatible calls share a backend until their last subscription is cancelled. Glob descriptions
251--- are compared by value, LPeg patterns by identity. Failed or replaced roots are never reused.
252--- @param name 'watch'|'watchdirs'|'inotify'
253--- @param backend vim._watch.Backend
254--- @param path string|vim._watch.Rule[]
255--- @param opts vim._watch.watch.Opts?
256--- @param callback vim._watch.Callback
257--- @return fun()
258local function start_watch(name, backend, path, opts, callback)
259  vim.validate('path', path, { 'string', 'table' })
260  vim.validate('opts', opts, 'table', true)
261  vim.validate('callback', callback, 'function')
262
263  opts = opts or {}
264  local on_error = opts.on_error or log.error
265
266  if type(path) == 'string' then
267    path = { { path = path } }
268  end
269
270  --- @type table<string, {pattern: vim._watch.Filter?, events: vim._watch.FileChangeType[]?}[]>
271  local by_path = vim.defaulttable()
272
273  for _, rule in ipairs(path) do
274    table.insert(
275      by_path[vim.fs.normalize(rule.path)],
276      { pattern = rule.pattern, events = rule.events }
277    )
278  end
279
280  local cancels = {} --- @type (fun())[]
281
282  local function cancel_all()
283    for _, cancel in ipairs(cancels) do
284      cancel()
285    end
286  end
287
288  for root, rules in pairs(by_path) do
289    local ok, result = pcall(subscribe, name, backend, root, opts, rules, {
290      callback = callback,
291      on_error = function(err)
292        on_error(('%s (watching %s)'):format(err, root))
293      end,
294    })
295
296    if not ok then
297      cancel_all()
298      error(result, 0)
299    end
300
301    cancels[#cancels + 1] = result
302  end
303
304  return cancel_all
305end
306
307--- Decides if `path` should be skipped.
308---
309--- @param path string
310--- @param opts vim._watch.BackendOpts
311--- @param directory? boolean Ignore include_pattern when traversing directories.
312local function skip(path, opts, directory)
313  if not directory and opts.include_pattern and opts.include_pattern:match(path) == nil then
314    return true
315  end
316
317  if opts.exclude_pattern and opts.exclude_pattern:match(path) ~= nil then
318    return true
319  end
320
321  return false
322end
323
324--- Initializes and starts a |uv_fs_event_t|
325---
326--- @param path string The path to watch
327--- @param opts vim._watch.BackendOpts Additional options:
328---      - uvflags (table|nil)
329---                 Same flags as accepted by |uv.fs_event_start()|
330--- @param callback vim._watch.Callback Callback for new events
331--- @return fun()? cancel Stops the watcher; nil if startup failed.
332local function watch(path, opts, callback)
333  local on_error = opts.on_error
334  local handle = assert(uv.new_fs_event())
335
336  local watching_dir = (uv.fs_stat(path) or {}).type == 'directory'
337
338  local _, start_err = handle:start(path, opts.uvflags or {}, function(err, filename, events)
339    if err then
340      return on_error(err)
341    end
342    local fullpath = path
343    if filename and watching_dir then
344      fullpath = vim.fs.normalize(vim.fs.joinpath(fullpath, filename))
345    end
346
347    if skip(fullpath, opts) then
348      return
349    end
350
351    --- @type vim._watch.FileChangeType
352    local change_type
353    if events.rename then
354      local _, staterr, staterrname = uv.fs_stat(fullpath)
355      if staterrname == 'ENOENT' then
356        change_type = M.FileChangeType.Deleted
357      else
358        if staterr then
359          return on_error(staterr)
360        end
361        change_type = M.FileChangeType.Created
362      end
363    elseif events.change then
364      change_type = M.FileChangeType.Changed
365    end
366    callback(fullpath, change_type)
367  end)
368
369  if start_err then
370    handle:close()
371    on_error(start_err)
372    return nil
373  end
374
375  return function()
376    local _, stop_err = handle:stop()
377    assert(not stop_err, stop_err)
378    local is_closing, close_err = handle:is_closing()
379    assert(not close_err, close_err)
380    if not is_closing then
381      handle:close()
382    end
383  end
384end
385
386--- Initializes and starts a |uv_fs_event_t| recursively watching every directory underneath the
387--- directory at path.
388---
389--- @param path string The path to watch. Must refer to a directory.
390--- @param opts vim._watch.BackendOpts Additional options
391--- @param callback vim._watch.Callback Callback for new events
392--- @return fun()? cancel Stops all directory watchers; nil if startup failed.
393local function watchdirs(path, opts, callback)
394  local on_error = opts.on_error
395  local debounce = opts.debounce or 500
396  local cancelled = false
397
398  ---@type table<string, uv.uv_fs_event_t> handle by fullpath
399  local handles = {}
400
401  local timer = assert(uv.new_timer())
402
403  --- Map of file path to boolean indicating if the file has been changed
404  --- at some point within the debounce cycle.
405  --- @type table<string, boolean>
406  local filechanges = {}
407
408  local process_changes --- @type fun()
409
410  --- @param filepath string
411  --- @return uv.fs_event_start.callback
412  local function create_on_change(filepath)
413    return function(err, filename, events)
414      if cancelled then
415        return
416      end
417      if err then
418        return on_error(err)
419      end
420
421      local fullpath = vim.fs.joinpath(filepath, filename)
422      if skip(fullpath, opts) then
423        -- An unmatched directory can contain matching descendants. Track its creation/deletion
424        -- even when no event for the directory itself will be reported.
425        if
426          skip(fullpath, opts, true)
427          or not events.rename
428          or (not handles[fullpath] and (uv.fs_stat(fullpath) or {}).type ~= 'directory')
429        then
430          return
431        end
432      end
433
434      if not filechanges[fullpath] then
435        filechanges[fullpath] = events.change or false
436      end
437      timer:start(debounce, 0, process_changes)
438    end
439  end
440
441  process_changes = function()
442    -- Since the callback is debounced it may have also been deleted later on
443    -- so we always need to check the existence of the file:
444    --   stat succeeds, changed=true  -> Changed
445    --   stat succeeds, changed=false -> Created
446    --   stat fails                   -> Removed
447    for fullpath, changed in pairs(filechanges) do
448      uv.fs_stat(fullpath, function(_, stat)
449        if cancelled then
450          return
451        end
452
453        ---@type vim._watch.FileChangeType
454        local change_type
455        if stat then
456          change_type = changed and M.FileChangeType.Changed or M.FileChangeType.Created
457          if stat.type == 'directory' then
458            local handle = handles[fullpath]
459            if not handle then
460              handle = assert(uv.new_fs_event())
461              handles[fullpath] = handle
462              local _, err, errname = handle:start(fullpath, {}, create_on_change(fullpath))
463              if err then
464                handle:close()
465                handles[fullpath] = nil
466                -- The directory may have disappeared since fs_stat().
467                if errname ~= 'ENOENT' then
468                  on_error(err)
469                end
470              end
471            end
472          end
473        else
474          change_type = M.FileChangeType.Deleted
475          local handle = handles[fullpath]
476          if handle then
477            if not handle:is_closing() then
478              handle:close()
479            end
480            handles[fullpath] = nil
481          end
482        end
483
484        if not skip(fullpath, opts) then
485          callback(fullpath, change_type)
486        end
487      end)
488    end
489    filechanges = {}
490  end
491
492  local root_handle = assert(uv.new_fs_event())
493  handles[path] = root_handle
494  local _, start_err = root_handle:start(path, {}, create_on_change(path))
495
496  if start_err then
497    root_handle:close()
498    timer:close()
499    on_error(start_err)
500    return nil
501  end
502
503  --- "640K ought to be enough for anyone"
504  --- Who has folders this deep?
505  local max_depth = 100
506
507  for name, type in
508    vim.fs.dir(path, {
509      depth = max_depth,
510      skip = function(dir)
511        return not opts.exclude_pattern
512          or opts.exclude_pattern:match(vim.fs.joinpath(path, dir)) == nil
513      end,
514    })
515  do
516    if type == 'directory' then
517      local filepath = vim.fs.joinpath(path, name)
518      if not skip(filepath, opts, true) then
519        local handle = assert(uv.new_fs_event())
520        handles[filepath] = handle
521        local _, err, errname = handle:start(filepath, {}, create_on_change(filepath))
522        if err then
523          handle:close()
524          handles[filepath] = nil
525          -- The directory may have disappeared since it was listed.
526          if errname ~= 'ENOENT' then
527            on_error(err)
528          end
529        end
530      end
531    end
532  end
533
534  return function()
535    cancelled = true
536    for fullpath, handle in pairs(handles) do
537      if not handle:is_closing() then
538        handle:close()
539      end
540      handles[fullpath] = nil
541    end
542    timer:stop()
543    timer:close()
544  end
545end
546
547--- @param data string
548--- @param opts vim._watch.BackendOpts
549--- @param callback vim._watch.Callback
550local function on_inotifywait_output(data, opts, callback)
551  local d = vim.split(data, '%s+')
552
553  -- only consider the last reported event
554  local path, event, file = assert(d[1]), d[2], d[#d]
555  local fullpath = vim.fs.joinpath(path, file)
556
557  if skip(fullpath, opts) then
558    return
559  end
560
561  --- @type integer
562  local change_type
563
564  if event == 'CREATE' then
565    change_type = M.FileChangeType.Created
566  elseif event == 'DELETE' then
567    change_type = M.FileChangeType.Deleted
568  elseif event == 'MODIFY' then
569    change_type = M.FileChangeType.Changed
570  elseif event == 'MOVED_FROM' then
571    change_type = M.FileChangeType.Deleted
572  elseif event == 'MOVED_TO' then
573    change_type = M.FileChangeType.Created
574  end
575
576  if change_type then
577    callback(fullpath, change_type)
578  end
579end
580
581--- @param path string The path to watch. Must refer to a directory.
582--- @param opts vim._watch.BackendOpts
583--- @param callback vim._watch.Callback Callback for new events
584--- @return fun()? cancel Stops the process; nil if startup failed.
585local function inotify(path, opts, callback)
586  local on_error = opts.on_error
587  local cancelled = false
588  local ok, obj = pcall(vim.system, {
589    'inotifywait',
590    '--quiet', -- suppress startup messages
591    '--no-dereference', -- don't follow symlinks
592    '--monitor', -- keep listening for events forever
593    '--recursive',
594    '--event',
595    'create',
596    '--event',
597    'delete',
598    '--event',
599    'modify',
600    '--event',
601    'move',
602    string.format('@%s/.git', path), -- ignore git directory
603    path,
604  }, {
605    stderr = function(err, data)
606      if err then
607        on_error(err)
608        return
609      end
610
611      if data and #vim.trim(data) > 0 then
612        if vim.fn.has('linux') == 1 and vim.startswith(data, 'Failed to watch') then
613          data = 'inotify(7) limit reached, see :h inotify-limitations for more info.'
614        end
615        on_error(data)
616      end
617    end,
618    stdout = function(err, data)
619      if err then
620        on_error(err)
621        return
622      end
623
624      for line in vim.gsplit(data or '', '\n', { plain = true, trimempty = true }) do
625        on_inotifywait_output(line, opts, callback)
626      end
627    end,
628    -- --latency is locale dependent but tostring() isn't and will always have '.' as decimal point.
629    env = { LC_NUMERIC = 'C' },
630  }, function(result)
631    if not cancelled then
632      on_error(('inotifywait exited with code %d'):format(result.code))
633    end
634  end)
635
636  if not ok then
637    on_error(obj)
638    return nil
639  end
640
641  return function()
642    cancelled = true
643    obj:kill(2)
644  end
645end
646
647--- Watches a path or set of rules. Compatible subscriptions share a backend watcher.
648--- @param path string|vim._watch.Rule[]
649--- @param opts? vim._watch.watch.Opts
650--- @param callback vim._watch.Callback
651--- @return fun() cancel Releases this subscription; the last cancellation stops the backend.
652function M.watch(path, opts, callback)
653  return start_watch('watch', watch, path, opts, callback)
654end
655
656--- Recursively watches directories. Compatible subscriptions share a backend watcher.
657--- @param path string|vim._watch.Rule[] Roots must be directories.
658--- @param opts? vim._watch.Opts
659--- @param callback vim._watch.Callback
660--- @return fun() cancel Releases this subscription; the last cancellation stops the backend.
661function M.watchdirs(path, opts, callback)
662  return start_watch('watchdirs', watchdirs, path, opts, callback)
663end
664
665--- Recursively watches directories using inotifywait. Compatible subscriptions share a process.
666--- @param path string|vim._watch.Rule[] Roots must be directories.
667--- @param opts? vim._watch.Opts
668--- @param callback vim._watch.Callback
669--- @return fun() cancel Releases this subscription; the last cancellation stops the backend.
670function M.inotify(path, opts, callback)
671  return start_watch('inotify', inotify, path, opts, callback)
672end
673
674return M