robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
6.7 KiB203 linesraw
1local bit = require('bit')
2local watch = vim._watch
3local log = require('vim.lsp.log')
4local notify = require('vim._core.util').notify
5local protocol = require('vim.lsp.protocol')
6
7local M = {}
8
9if vim.fn.has('win32') == 1 or vim.fn.has('mac') == 1 then
10  M._watchfunc = watch.watch
11elseif vim.fn.executable('inotifywait') == 1 then
12  M._watchfunc = watch.inotify
13else
14  M._watchfunc = watch.watchdirs
15end
16
17--- @type table<integer, table<string, fun()>> client id -> registration id -> cancel
18local registered = vim.defaulttable(function()
19  return {}
20end)
21
22local queue_timeout_ms = 100
23---@type table<integer, uv.uv_timer_t> client id -> libuv timer which will send queued changes at its timeout
24local queue_timers = {}
25---@type table<integer, lsp.FileEvent[]> client id -> set of queued changes to send in a single LSP notification
26local change_queues = {}
27---@type table<integer, table<string, lsp.FileChangeType>> client id -> URI -> last type of change processed
28--- Used to prune consecutive events of the same type for the same file
29local change_cache = vim.defaulttable()
30
31---@type table<vim._watch.FileChangeType, lsp.FileChangeType>
32local to_lsp_change_type = {
33  [watch.FileChangeType.Created] = protocol.FileChangeType.Created,
34  [watch.FileChangeType.Changed] = protocol.FileChangeType.Changed,
35  [watch.FileChangeType.Deleted] = protocol.FileChangeType.Deleted,
36}
37
38--- Default excludes the same as VSCode's `files.watcherExclude` setting.
39--- https://github.com/microsoft/vscode/blob/eef30e7165e19b33daa1e15e92fa34ff4a5df0d3/src/vs/workbench/contrib/files/browser/files.contribution.ts#L261
40--- @type vim._watch.Filter
41M._poll_exclude_pattern = {
42  '**/.git/{objects,subtree-cache}/**',
43  '**/node_modules/*/**',
44  '**/.hg/store/**',
45}
46
47--- Resolves LSP workspace folders and relative patterns into filesystem watcher rules.
48--- @param watchers lsp.FileSystemWatcher[]
49--- @param workspace_folders lsp.WorkspaceFolder[]
50--- @return vim._watch.Rule[]
51local function watcher_rules(watchers, workspace_folders)
52  local rules = {} --- @type vim._watch.Rule[]
53
54  for _, w in ipairs(watchers) do
55    local events --- @type vim._watch.FileChangeType[]?
56    if w.kind then
57      events = {}
58      for change_type, lsp_change_type in pairs(to_lsp_change_type) do
59        -- WatchKind is a bitmask, whereas FileChangeType is an enum.
60        if
61          bit.band(w.kind, bit.lshift(1, (lsp_change_type - 1) --[[@as integer]])) ~= 0
62        then
63          table.insert(events, change_type)
64        end
65      end
66    end
67
68    local pattern = w.globPattern
69    if type(pattern) == 'string' then
70      for _, folder in ipairs(workspace_folders) do
71        rules[#rules + 1] =
72          { path = vim.uri_to_fname(folder.uri), pattern = pattern, events = events }
73      end
74    else
75      local uri = type(pattern.baseUri) == 'string' and pattern.baseUri or pattern.baseUri.uri
76      local base = vim.uri_to_fname(uri)
77      local prefix = vim.fs.normalize(base):gsub('/$', '')
78
79      rules[#rules + 1] = {
80        path = base,
81        -- Keep the base literal. '/' handles UNC paths; '#' avoids the parser's leading marker.
82        pattern = vim.fn.escape(prefix, '\\/*?[]{}#') .. '/' .. pattern.pattern,
83        events = events,
84      }
85    end
86  end
87
88  return rules
89end
90
91--- @param client vim.lsp.Client
92--- @param err string
93local function report_error(client, err)
94  local name = string.format('LSP[%s]', client.name)
95  local message = 'file watcher failed: ' .. err
96  local level = vim.log.levels.ERROR
97
98  -- Servers may register a nonexistent baseUri. Keep this informational
99  -- and continue registering the other watchers.
100  if err:match('^ENOENT:') then
101    level = vim.log.levels.INFO
102    log.info(name, message)
103  else
104    log.error(name, message)
105  end
106
107  notify(name, message, level, true)
108end
109
110--- Queues a file change, pruning consecutive duplicates per URI.
111--- Changes are batched into a single notification per client.
112---
113--- @param client vim.lsp.Client
114--- @param fullpath string
115--- @param change_type vim._watch.FileChangeType
116local function queue_change(client, fullpath, change_type)
117  local client_id = client.id
118  --- @type lsp.FileEvent
119  local change = {
120    uri = vim.uri_from_fname(fullpath),
121    type = to_lsp_change_type[change_type],
122  }
123
124  local last_type = change_cache[client_id][change.uri]
125  if last_type ~= change.type then
126    change_queues[client_id] = change_queues[client_id] or {}
127    table.insert(change_queues[client_id], change)
128    change_cache[client_id][change.uri] = change.type
129  end
130
131  if not queue_timers[client_id] then
132    queue_timers[client_id] = vim.defer_fn(function()
133      --- @type lsp.DidChangeWatchedFilesParams
134      local params = { changes = change_queues[client_id] }
135      client:notify('workspace/didChangeWatchedFiles', params)
136
137      queue_timers[client_id] = nil
138      change_queues[client_id] = nil
139      change_cache[client_id] = nil
140    end, queue_timeout_ms)
141  end
142end
143
144--- Registers the workspace/didChangeWatchedFiles capability dynamically.
145---
146---@param reg lsp.Registration LSP Registration object.
147---@param client_id integer Client ID.
148function M.register(reg, client_id)
149  local client = assert(vim.lsp.get_client_by_id(client_id), 'Client must be running')
150  -- Ill-behaved servers may not honor the client capability and try to register
151  -- anyway, so ignore requests when the user has opted out of the feature.
152  local has_capability =
153    vim.tbl_get(client.capabilities, 'workspace', 'didChangeWatchedFiles', 'dynamicRegistration')
154  if not has_capability or not client.workspace_folders then
155    return
156  end
157
158  local options = reg.registerOptions --[[@as lsp.DidChangeWatchedFilesRegistrationOptions]]
159  local rules = watcher_rules(options.watchers, client.workspace_folders)
160
161  local cancel = M._watchfunc(rules, {
162    uvflags = { recursive = true },
163    exclude_pattern = M._poll_exclude_pattern,
164    on_error = function(err)
165      report_error(client, err)
166    end,
167  }, function(fullpath, change_type)
168    queue_change(client, fullpath, change_type)
169  end)
170
171  -- Acquire first so replacing an ID does not stop a shared backend between subscriptions.
172  M.unregister(reg.id, client_id)
173  registered[client_id][reg.id] = cancel
174end
175
176--- Unregisters the workspace/didChangeWatchedFiles capability dynamically.
177---
178--- @param id string Registration ID.
179--- @param client_id integer Client ID.
180function M.unregister(id, client_id)
181  local client_registrations = registered[client_id]
182  local cancel = client_registrations[id]
183
184  client_registrations[id] = nil
185  if not next(client_registrations) then
186    registered[client_id] = nil
187  end
188
189  if cancel then
190    cancel()
191  end
192end
193
194--- @param client_id integer
195function M.cancel(client_id)
196  for id in pairs(registered[client_id]) do
197    M.unregister(id, client_id)
198  end
199
200  registered[client_id] = nil
201end
202
203return M