-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapi.lua
More file actions
462 lines (406 loc) · 13.3 KB
/
api.lua
File metadata and controls
462 lines (406 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
---For newcommers, in the original `project.nvim` this file was
---`project.lua`. I decided to make this an API file instead
---to avoid any confusions with naming,
---e.g. `require('project_nvim.project')`.
---@enum (key) ProjectPaths
local project_paths = { ---@diagnostic disable-line:unused-local
datapath = 1,
historyfile = 1,
projectpath = 1,
}
---@class HistoryPath
---@field datapath string
---@field projectpath string
---@field historyfile string
local MODSTR = 'project.api'
local ERROR = vim.log.levels.ERROR
local INFO = vim.log.levels.INFO
local uv = vim.uv or vim.loop
local Config = require('project.config')
local Path = require('project.util.path')
local Util = require('project.util')
local History = require('project.util.history')
local Log = require('project.util.log')
---The `project.nvim` API module.
--- ---
---@class Project.API
---@field last_project? string
---@field current_project? string
---@field current_method? string
local Api = {}
---@class ProjectRootSwitch
local SWITCH = {}
---@param bufnr? integer
---@return boolean success
---@return string|nil root
---@return string|nil method
---@nodiscard
function SWITCH.lsp(bufnr)
Util.validate({ bufnr = { bufnr, { 'number', 'nil' }, true } })
bufnr = (bufnr and Util.is_int(bufnr, bufnr >= 0)) and bufnr or vim.api.nvim_get_current_buf()
local root, lsp_name = Api.find_lsp_root(bufnr or vim.api.nvim_get_current_buf())
if root then
return true, root, ('"%s" lsp'):format(lsp_name)
end
return false
end
---@param bufnr? integer
---@return boolean success
---@return string|nil root
---@return string|nil method
---@nodiscard
function SWITCH.pattern(bufnr)
Util.validate({ bufnr = { bufnr, { 'number', 'nil' }, true } })
bufnr = (bufnr and Util.is_int(bufnr, bufnr >= 0)) and bufnr or vim.api.nvim_get_current_buf()
local root, method = Api.find_pattern_root(bufnr or vim.api.nvim_get_current_buf())
if root then
return true, root, method
end
return false
end
---@param bufnr integer
---@return boolean valid
---@nodiscard
function Api.buffer_valid(bufnr)
Util.validate({ bufnr = { bufnr, { 'number' } } })
return vim.api.nvim_buf_is_valid(bufnr) and vim.api.nvim_buf_is_loaded(bufnr)
end
---@param bufnr? integer
---@return string|nil dir
---@nodiscard
function Api.check_oil(bufnr)
Util.validate({ bufnr = { bufnr, { 'number', 'nil' }, true } })
bufnr = (bufnr and Util.is_int(bufnr, bufnr >= 0)) and bufnr or vim.api.nvim_get_current_buf()
local bufname = vim.api.nvim_buf_get_name(bufnr)
local ok, oil = pcall(require, 'oil')
local dir ---@type string|nil
---SOURCE: https://github.com/cosmicbuffalo/root_swapper.nvim/blob/main/lua/root_swapper.lua
dir = (ok and oil and oil.get_current_dir) and oil.get_current_dir(bufnr)
or bufname:gsub('^oil://', '')
if dir then
dir = Util.rstrip('/', dir)
end
return dir
end
---@return string|nil last
---@nodiscard
function Api.get_last_project()
local recent = History.get_recent_projects()
if vim.tbl_isempty(recent) or #recent == 1 then
return
end
recent = Util.reverse(recent) --[[@as string[]\]]
return #History.session_projects <= 1 and recent[2] or recent[1]
end
---@param path? ProjectPaths
---@return string|HistoryPath history_paths
---@nodiscard
function Api.get_history_paths(path)
Util.validate({ path = { path, { 'string', 'nil' }, true } })
local res = { ---@type HistoryPath
datapath = Path.datapath,
projectpath = Path.projectpath,
historyfile = Path.historyfile,
}
if path and vim.list_contains(vim.tbl_keys(res), path) then
return Path[path]
end
return res
end
---Get the LSP client for current buffer.
---
---If successful, returns a tuple of two `string` results.
---Otherwise, nothing is returned.
--- ---
---@param bufnr? integer
---@return string|nil dir
---@return string|nil name
---@nodiscard
function Api.find_lsp_root(bufnr)
Util.validate({ bufnr = { bufnr, { 'number', 'nil' }, true } })
bufnr = (bufnr and Util.is_int(bufnr, bufnr >= 0)) and bufnr or vim.api.nvim_get_current_buf()
local clients = vim.lsp.get_clients({ bufnr = bufnr })
if vim.tbl_isempty(clients) then
return
end
local ignore_lsp = Config.options.lsp.ignore
local ft = Util.optget('filetype', 'buf', bufnr)
for _, client in ipairs(clients) do
local filetypes = client.config.filetypes --[[@as string[]\]]
local valid = (
Util.is_type('table', filetypes)
and vim.list_contains(filetypes, ft)
and not vim.list_contains(ignore_lsp, client.name)
and client.config.root_dir
)
if valid then
if
Config.options.lsp.use_pattern_matching
and Path.root_included(client.config.root_dir) == nil
then
return
end
return client.config.root_dir, client.name
end
end
end
---@param bufnr? integer
---@return string|nil dir_res
---@return string|nil method
---@nodiscard
function Api.find_pattern_root(bufnr)
Util.validate({ bufnr = { bufnr, { 'number', 'nil' }, true } })
bufnr = (bufnr and Util.is_int(bufnr, bufnr >= 0)) and bufnr or vim.api.nvim_get_current_buf()
local bufname = vim.api.nvim_buf_get_name(bufnr)
local dir = Api.check_oil(bufnr) or '' ---@type string
dir = dir == '' and vim.fn.fnamemodify(bufname, ':p:h') or dir
dir = Util.is_windows() and dir:gsub('\\', '/') or dir
return Path.root_included(dir)
end
---@param bufnr? integer
---@return boolean valid
---@nodiscard
function Api.valid_bt(bufnr)
Util.validate({ bufnr = { bufnr, { 'number', 'nil' }, true } })
bufnr = (bufnr and Util.is_int(bufnr, bufnr >= 0)) and bufnr or vim.api.nvim_get_current_buf()
if not Api.buffer_valid(bufnr) then
return false
end
local bt = Util.optget('buftype', 'buf', bufnr)
return not vim.list_contains(Config.options.disable_on.bt, bt)
end
---Generates the autocommand for the `LspAttach` event.
---
---**_An `augroup` ID is mandatory!_**
--- ---
---@param group integer
function Api.gen_lsp_autocmd(group)
Util.validate({ group = { group, { 'number' } } })
if not Util.is_int(group) then
error(('Parameter group is not an integer `%s`'):format(group))
end
if vim.g.project_lspattach == 1 then
return
end
vim.api.nvim_create_autocmd('LspAttach', {
group = group,
nested = true,
callback = function(ev)
Api.on_buf_enter(ev.buf)
end,
})
vim.g.project_lspattach = 1
end
---@param dir string
---@param method string
---@return boolean success
function Api.set_pwd(dir, method)
Util.validate({
dir = { dir, { 'string' } },
method = { method, { 'string' } },
})
dir = vim.fn.expand(dir)
if not Path.verify_owner(dir) then
Log.warn(('(%s.set_pwd): Project is owned by a different user'):format(MODSTR))
if Config.options.different_owners.notify then
vim.notify(('(%s.set_pwd): Project is owned by a different user'):format(MODSTR), ERROR)
end
if not Config.options.different_owners.allow then
return false
end
end
local modified = false
local unexpand_dir = Util.rstrip('/', vim.fn.fnamemodify(dir, ':p:~'))
if not (History.session_projects and vim.list_contains(History.session_projects, dir)) then
table.insert(History.session_projects, dir)
modified = true
Log.debug(('Added project %s to the top of session list'):format(unexpand_dir))
end
if not modified and #History.session_projects > 1 then
local old_pos ---@type integer
for k, v in ipairs(History.session_projects) do
if v == dir then
old_pos = k
break
end
end
if old_pos ~= 1 then
table.remove(History.session_projects, old_pos)
table.insert(History.session_projects, 1, dir) -- HACK: Move project to start of table
Log.debug(
('Moved project %s from %d to the top of session list'):format(unexpand_dir, old_pos)
)
end
end
if Config.options.before_attach then
Config.options.before_attach(dir, method)
Log.debug('Ran `before_attach` hook successfully.')
end
local cwd = uv.cwd() or vim.fn.getcwd()
if dir == Util.rstrip('/', cwd) then
Api.current_project = dir
Api.current_method = method
if vim.g.project_cwd_log ~= 1 then
Log.info(('(%s.set_pwd): Current directory is selected project.'):format(MODSTR))
end
vim.g.project_cwd_log = 1
return true
end
local scope_chdir = Config.options.scope_chdir
local msg = ('(%s.set_pwd):'):format(MODSTR)
if not vim.list_contains({ 'global', 'tab', 'win' }, scope_chdir) then
Log.error(('%s INVALID value for `scope_chdir`: `%s`'):format(msg, vim.inspect(scope_chdir)))
vim.notify(
('%s INVALID value for `scope_chdir`: `%s`'):format(msg, vim.inspect(scope_chdir)),
ERROR
)
end
vim.g.project_cwd_log = 0
local ok = false
if scope_chdir == 'global' then
ok = pcall(vim.api.nvim_set_current_dir, dir)
msg = ('%s\nchdir: `%s`:'):format(msg, dir)
elseif scope_chdir == 'tab' then
ok = pcall(vim.cmd.tchdir, dir)
msg = ('%s\ntchdir: `%s`:'):format(msg, dir)
elseif scope_chdir == 'win' then
ok = pcall(vim.cmd.lchdir, dir)
msg = ('%s\nlchdir: `%s`:'):format(msg, dir)
end
msg = ('%s\nMethod: %s\nStatus: %s'):format(msg, method, (ok and 'SUCCESS' or 'FAILED'))
if ok then
Api.current_project = dir
Api.current_method = method
Log.info(msg)
if Config.options.on_attach then
Config.options.on_attach(dir, method)
Log.debug('Ran `on_attach` hook successfully.')
end
else
Log.error(msg)
end
if not Config.options.silent_chdir then
vim.schedule(function()
vim.notify(msg, (ok and INFO or ERROR))
end)
end
if ok then
Log.debug(('Changed directory to `%s` using method `%s`'):format(dir, method))
History.write_history()
end
return ok
end
---Returns the project root, as well as the method used.
---
---If no project root is found, nothing will be returned.
--- ---
---@param bufnr? integer
---@return string|nil root
---@return string|nil method
---@nodiscard
function Api.get_project_root(bufnr)
Util.validate({ bufnr = { bufnr, { 'number', 'nil' }, true } })
bufnr = (bufnr and Util.is_int(bufnr, bufnr >= 0)) and bufnr or vim.api.nvim_get_current_buf()
if not Api.buffer_valid(bufnr) or vim.tbl_isempty(Config.detection_methods) then
return
end
local roots = {} ---@type { root: string, method_msg: string, method: 'lsp'|'pattern' }[]
local root, method = nil, nil
local ops = vim.tbl_keys(SWITCH) ---@type ('lsp'|'pattern')[]
local success = false
for _, m in ipairs(Config.detection_methods) do
if vim.list_contains(ops, m) then
---@type boolean, string|nil, string|nil
success, root, method = SWITCH[m](bufnr)
if success then
table.insert(roots, { root = root, method_msg = method, method = m })
end
end
end
if vim.tbl_isempty(roots) then
return
end
if #roots == 1 or Config.options.lsp.no_fallback then
return roots[1].root, roots[1].method_msg
end
if roots[1].root == roots[2].root then
return roots[1].root, roots[1].method_msg
end
for _, tbl in ipairs(roots) do
if tbl.method == 'pattern' then
return tbl.root, tbl.method_msg
end
end
end
---CREDITS: https://github.com/ahmedkhalf/project.nvim/pull/149
--- ---
---@param bufnr? integer
---@return string|nil curr
---@return string|nil method
---@return string|nil last
---@nodiscard
function Api.get_current_project(bufnr)
Util.validate({ bufnr = { bufnr, { 'number', 'nil' }, true } })
bufnr = (bufnr and Util.is_int(bufnr, bufnr >= 0)) and bufnr or vim.api.nvim_get_current_buf()
if not Api.buffer_valid(bufnr) then
return
end
local curr, method = Api.get_project_root(bufnr)
local last = Api.get_last_project()
return curr, method, last
end
---@param bufnr? integer
function Api.on_buf_enter(bufnr)
Util.validate({ bufnr = { bufnr, { 'number', 'nil' }, true } })
bufnr = (bufnr and Util.is_int(bufnr, bufnr >= 0)) and bufnr or vim.api.nvim_get_current_buf()
if not (Api.buffer_valid(bufnr) and Api.valid_bt(bufnr)) then
return
end
local bufname = vim.api.nvim_buf_get_name(bufnr)
local dir = Api.check_oil(bufnr) or ''
dir = Util.rstrip(
'/',
dir == '' and vim.fn.fnamemodify(bufname, ':p:h') or vim.fn.fnamemodify(dir, ':p')
)
dir = Util.is_windows() and dir:gsub('\\', '/') or dir
if not (Path.exists(dir) and Path.root_included(dir)) or Path.is_excluded(dir) then
return
end
local ft = Util.optget('filetype', 'buf', bufnr)
if vim.list_contains(Config.options.disable_on.ft, ft) then
return
end
Api.current_project, Api.current_method = Api.get_current_project(bufnr)
local change = Api.current_project ~= (uv.cwd() or vim.fn.getcwd())
Api.set_pwd(Api.current_project, Api.current_method)
if change then
Api.last_project = Api.get_last_project()
end
History.write_history()
end
function Api.init()
local group = vim.api.nvim_create_augroup('project.nvim', { clear = true })
vim.api.nvim_create_autocmd('VimLeavePre', {
group = group,
callback = function()
History.write_history()
end,
})
if not Config.options.manual_mode then
if vim.list_contains(Config.detection_methods, 'pattern') then
vim.api.nvim_create_autocmd('BufEnter', {
group = group,
nested = true,
callback = function(ev)
Api.on_buf_enter(ev.buf)
end,
})
end
if vim.list_contains(Config.detection_methods, 'lsp') then
Api.gen_lsp_autocmd(group)
end
end
History.read_history()
end
return Api
-- vim: set ts=2 sts=2 sw=2 et ai si sta: