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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
|
local pub = require 'pub'
local fs = require 'bee.filesystem'
local furi = require 'file-uri'
local files = require 'files'
local config = require 'config'
local glob = require 'glob'
local platform = require 'bee.platform'
local await = require 'await'
local proto = require 'proto.proto'
local lang = require 'language'
local library = require 'library'
local progress = require 'progress'
local define = require "proto.define"
local client = require 'client'
local m = {}
m.type = 'workspace'
m.nativeVersion = -1
m.libraryVersion = -1
m.nativeMatcher = nil
m.fileLoaded = 0
m.fileFound = 0
m.waitingReady = {}
m.requireCache = {}
m.cache = {}
m.matchOption = {
ignoreCase = platform.OS == 'Windows',
}
--- 初始化工作区
function m.init(uri)
log.info('Workspace inited: ', uri)
if not uri then
return
end
m.uri = uri
m.path = m.normalize(furi.decode(uri))
local logPath = fs.path(LOGPATH) / (uri:gsub('[/:]+', '_') .. '.log')
client.logMessage('Log', 'Log path: ' .. furi.encode(logPath:string()))
log.info('Log path: ', logPath)
log.init(ROOT, logPath)
end
local globInteferFace = {
type = function (path)
local result
pcall(function ()
if fs.is_directory(fs.path(path)) then
result = 'directory'
else
result = 'file'
end
end)
return result
end,
list = function (path)
local fullPath = fs.path(path)
if not fs.exists(fullPath) then
return nil
end
local paths = {}
pcall(function ()
for fullpath in fullPath:list_directory() do
paths[#paths+1] = fullpath:string()
end
end)
return paths
end
}
--- 创建排除文件匹配器
function m.getNativeMatcher()
if not m.path then
return nil
end
if m.nativeMatcher then
return m.nativeMatcher
end
local pattern = {}
-- config.get 'workspace.ignoreDir'
for path in pairs(config.get 'Lua.workspace.ignoreDir') do
log.info('Ignore directory:', path)
pattern[#pattern+1] = path
end
-- config.get 'files.exclude'
for path, ignore in pairs(config.get 'files.exclude') do
if ignore then
log.info('Ignore by exclude:', path)
pattern[#pattern+1] = path
end
end
-- config.get 'workspace.ignoreSubmodules'
if config.get 'Lua.workspace.ignoreSubmodules' then
local buf = pub.awaitTask('loadFile', furi.encode(m.path .. '/.gitmodules'))
if buf then
for path in buf:gmatch('path = ([^\r\n]+)') do
log.info('Ignore by .gitmodules:', path)
pattern[#pattern+1] = path
end
end
end
-- config.get 'workspace.useGitIgnore'
if config.get 'Lua.workspace.useGitIgnore' then
local buf = pub.awaitTask('loadFile', furi.encode(m.path .. '/.gitignore'))
if buf then
for line in buf:gmatch '[^\r\n]+' do
if line:sub(1, 1) ~= '#' then
log.info('Ignore by .gitignore:', line)
pattern[#pattern+1] = line
end
end
end
buf = pub.awaitTask('loadFile', furi.encode(m.path .. '/.git/info/exclude'))
if buf then
for line in buf:gmatch '[^\r\n]+' do
if line:sub(1, 1) ~= '#' then
log.info('Ignore by .git/info/exclude:', line)
pattern[#pattern+1] = line
end
end
end
end
-- config.get 'workspace.library'
for path in pairs(config.get 'Lua.workspace.library') do
path = path:gsub('${(.-)}', {
meta = (ROOT / 'meta' / '3rd'):string(),
})
log.info('Ignore by library:', path)
pattern[#pattern+1] = path
end
m.nativeMatcher = glob.gitignore(pattern, m.matchOption, globInteferFace)
m.nativeMatcher:setOption('root', m.path)
m.nativeVersion = config.get 'version'
return m.nativeMatcher
end
--- 创建代码库筛选器
function m.getLibraryMatchers()
if m.libraryMatchers then
return m.libraryMatchers
end
local librarys = {}
for path in pairs(config.get 'Lua.workspace.library') do
path = path:gsub('${(.-)}', {
meta = (ROOT / 'meta' / '3rd'):string(),
})
librarys[m.normalize(path)] = true
end
if library.metaPath then
librarys[m.normalize(library.metaPath)] = true
end
m.libraryMatchers = {}
for path in pairs(librarys) do
if fs.exists(fs.path(path)) then
local nPath = fs.absolute(fs.path(path)):string()
local matcher = glob.gitignore(true, m.matchOption, globInteferFace)
matcher:setOption('root', path)
log.debug('getLibraryMatchers', path, nPath)
m.libraryMatchers[#m.libraryMatchers+1] = {
path = nPath,
matcher = matcher
}
end
end
m.libraryVersion = config.get 'version'
return m.libraryMatchers
end
--- 文件是否被忽略
function m.isIgnored(uri)
local path = m.getRelativePath(uri)
local ignore = m.getNativeMatcher()
if not ignore then
return false
end
return ignore(path)
end
local function loadFileFactory(root, progressData, isLibrary)
return function (path)
local uri = furi.encode(path)
if files.isLua(uri) then
if not isLibrary and progressData.preload >= config.get 'Lua.workspace.maxPreload' then
if not m.hasHitMaxPreload then
m.hasHitMaxPreload = true
proto.request('window/showMessageRequest', {
type = define.MessageType.Info,
message = lang.script('MWS_MAX_PRELOAD', config.get 'Lua.workspace.maxPreload'),
actions = {
{
title = lang.script.WINDOW_INCREASE_UPPER_LIMIT,
},
{
title = lang.script.WINDOW_CLOSE,
}
}
}, function (item)
if not item then
return
end
if item.title == lang.script.WINDOW_INCREASE_UPPER_LIMIT then
client.setConfig {
{
key = 'Lua.workspace.maxPreload',
action = 'set',
value = config.get 'Lua.workspace.maxPreload'
+ math.max(1000, config.get 'Lua.workspace.maxPreload'),
uri = m.uri,
}
}
end
end)
end
return
end
if not isLibrary then
progressData.preload = progressData.preload + 1
end
progressData.max = progressData.max + 1
progressData:update()
pub.task('loadFile', uri, function (text)
local loader = function ()
if text then
log.info(('Preload file at: %s , size = %.3f KB'):format(uri, #text / 1024.0))
if isLibrary then
log.info('++++As library of:', root)
files.setLibraryPath(uri, root)
end
files.setText(uri, text, false, true)
else
files.remove(uri)
end
progressData.read = progressData.read + 1
progressData:update()
end
if progressData.loaders then
progressData.loaders[#progressData.loaders+1] = loader
else
loader()
end
end)
end
if files.isDll(uri) then
progressData.max = progressData.max + 1
progressData:update()
pub.task('loadFile', uri, function (content)
if content then
log.info(('Preload file at: %s , size = %.3f KB'):format(uri, #content / 1024.0))
if isLibrary then
log.info('++++As library of:', root)
end
files.saveDll(uri, content)
end
progressData.read = progressData.read + 1
progressData:update()
end)
end
await.delay()
end
end
function m.awaitLoadFile(uri)
local progressBar <close> = progress.create(lang.script.WORKSPACE_LOADING)
local progressData = {
max = 0,
read = 0,
preload = 0,
update = function (self)
progressBar:setMessage(('%d/%d'):format(self.read, self.max))
progressBar:setPercentage(self.read / self.max * 100)
end
}
local nativeLoader = loadFileFactory(m.path, progressData)
local native = m.getNativeMatcher()
if native then
log.info('Scan files at:', m.path)
native:scan(furi.decode(uri), nativeLoader)
end
end
--- 预读工作区内所有文件
function m.awaitPreload()
local diagnostic = require 'provider.diagnostic'
await.close 'preload'
await.setID 'preload'
await.sleep(0.1)
diagnostic.pause()
m.libraryMatchers = nil
m.nativeMatcher = nil
m.fileLoaded = 0
m.fileFound = 0
m.cache = {}
local progressBar <close> = progress.create(lang.script.WORKSPACE_LOADING)
local progressData = {
max = 0,
read = 0,
preload = 0,
loaders = {},
update = function (self)
progressBar:setMessage(('%d/%d'):format(self.read, self.max))
progressBar:setPercentage(self.read / self.max * 100)
m.fileLoaded = self.read
m.fileFound = self.max
end
}
log.info('Preload start.')
local nativeLoader = loadFileFactory(m.path, progressData)
local native = m.getNativeMatcher()
local librarys = m.getLibraryMatchers()
if native then
log.info('Scan files at:', m.path)
native:scan(m.path, nativeLoader)
end
for _, library in ipairs(librarys) do
local libraryLoader = loadFileFactory(library.path, progressData, true)
log.info('Scan library at:', library.path)
library.matcher:scan(library.path, libraryLoader)
end
await.call(function ()
for _, loader in ipairs(progressData.loaders) do
loader()
await.delay()
end
end)
log.info(('Found %d files.'):format(progressData.max))
while true do
log.info(('Loaded %d/%d files'):format(progressData.read, progressData.max))
progressData:update()
if progressData.read >= progressData.max then
break
end
await.sleep(0.1)
end
progressBar:remove()
log.info('Preload finish.')
diagnostic.start()
end
--- 查找符合指定file path的所有uri
---@param path string
function m.findUrisByFilePath(path)
if type(path) ~= 'string' then
return {}
end
local lpath = furi.encode(path):gsub('^file:///', '')
if platform.OS == 'Windows' then
lpath = lpath:lower()
end
local vm = require 'vm'
local resultCache = vm.getCache 'findUrisByRequirePath.result'
if resultCache[path] then
return resultCache[path].results, resultCache[path].posts
end
tracy.ZoneBeginN('findUrisByFilePath #1')
local results = {}
local posts = {}
for uri in files.eachFile() do
if platform.OS ~= 'Windows' then
uri = files.getOriginUri(uri)
end
if not uri:find(lpath, 1, true) then
goto CONTINUE
end
local pathLen = #path
local curPath = furi.decode(files.getOriginUri(uri))
local curLen = #curPath
local seg = curPath:sub(curLen - pathLen, curLen - pathLen)
if seg == '/' or seg == '\\' or seg == '' then
local see = curPath:sub(curLen - pathLen + 1, curLen)
if files.eq(see, path) then
results[#results+1] = uri
local post = curPath:sub(1, curLen - pathLen)
posts[uri] = post:gsub('^[/\\]+', '')
end
end
::CONTINUE::
end
tracy.ZoneEnd()
resultCache[path] = {
results = results,
posts = posts,
}
return results, posts
end
--- 查找符合指定require path的所有uri
---@param path string
function m.findUrisByRequirePath(path)
if type(path) ~= 'string' then
return {}
end
local vm = require 'vm'
local cache = vm.getCache 'findUrisByRequirePath'
if cache[path] then
return cache[path].results, cache[path].searchers
end
tracy.ZoneBeginN('findUrisByRequirePath')
local results = {}
local mark = {}
local searchers = {}
for uri in files.eachDll() do
local opens = files.getDllOpens(uri) or {}
for _, open in ipairs(opens) do
if open == path then
results[#results+1] = uri
end
end
end
local input = path:gsub('%.', '/')
:gsub('%%', '%%%%')
for _, luapath in ipairs(config.get 'Lua.runtime.path') do
local part = m.normalize(luapath:gsub('%?', input))
local uris, posts = m.findUrisByFilePath(part)
for _, uri in ipairs(uris) do
if not mark[uri] then
mark[uri] = true
results[#results+1] = uri
searchers[uri] = posts[uri] .. luapath
end
end
end
tracy.ZoneEnd()
cache[path] = {
results = results,
searchers = searchers,
}
return results, searchers
end
function m.normalize(path)
if platform.OS == 'Windows' then
path = path:gsub('[/\\]+', '\\')
:gsub('[/\\]+$', '')
else
path = path:gsub('[/\\]+', '/')
:gsub('[/\\]+$', '')
end
return path
end
function m.getRelativePath(uri)
local path = furi.decode(uri)
if not m.path then
local relative = m.normalize(path)
return relative:gsub('^[/\\]+', '')
end
local _, pos
if platform.OS == 'Windows' then
_, pos = m.normalize(path):lower():find(m.path:lower(), 1, true)
else
_, pos = m.normalize(path):find(m.path, 1, true)
end
if pos then
return m.normalize(path:sub(pos + 1)):gsub('^[/\\]+', '')
else
return m.normalize(path):gsub('^[/\\]+', '')
end
end
function m.isWorkspaceUri(uri)
if not m.uri then
return false
end
local luri = files.getUri(uri)
local ruri = files.getUri(m.uri)
return luri:sub(1, #ruri) == ruri
end
--- 获取工作区等级的缓存
function m.getCache(name)
if not m.cache[name] then
m.cache[name] = {}
end
return m.cache[name]
end
function m.flushCache()
m.cache = {}
end
function m.reload()
await.call(m.awaitReload)
end
function m.awaitReload()
local plugin = require 'plugin'
m.ready = false
m.hasHitMaxPreload = false
files.flushAllLibrary()
files.removeAllClosed()
files.flushCache()
plugin.init()
m.awaitPreload()
m.ready = true
local waiting = m.waitingReady
m.waitingReady = {}
for _, waker in ipairs(waiting) do
waker()
end
end
---等待工作目录加载完成
function m.awaitReady()
if m.isReady() then
return
end
await.wait(function (waker)
m.waitingReady[#m.waitingReady+1] = waker
end)
end
function m.isReady()
return m.ready == true
end
function m.getLoadProcess()
return m.fileLoaded, m.fileFound
end
files.watch(function (ev, uri)
if ev == 'close'
and m.isIgnored(uri)
and not files.isLibrary(uri) then
files.remove(uri)
end
end)
config.watch(function (key, value, oldValue)
if key:find '^Lua.runtime'
or key:find '^Lua.workspace'
or key:find '^files' then
if value ~= oldValue then
m.reload()
end
end
end)
return m
|