Created
September 21, 2021 19:13
-
-
Save OttoHatt/36b75d2d4d340de88d2f0845d89e2b76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local fs = require("bee.filesystem") | |
local fsu = require("fs-utility") | |
local furi = require("file-uri") | |
local workspace = require("workspace") | |
local foundFileCache = {} | |
local function relativePathToDotPath(relPath) | |
-- Convert posix path to dots, and remove file extension. | |
return tostring(relPath):gsub(".lua", ""):gsub("\\", "."):gsub("/", ".") | |
end | |
function buildFileMap() | |
local projectRoot = fs.path(workspace.path) | |
fsu.scanDirectory(projectRoot / "src", function(path) | |
if path:extension():string() ~= ".lua" then return end | |
local uri = furi.encode(path:string()) | |
-- Check that this file isn't ignored, and isn't a library. | |
-- if (not workspace.isValidLuaUri(uri)) then return end | |
-- Get the relative pat to the workspace. | |
local relativePath = workspace.getRelativePath(uri) | |
foundFileCache[path:stem():string()] = relativePath | |
end) | |
end | |
function getLuaFile(fileName) | |
local path = foundFileCache[fileName] | |
if (path) and (fs.exists(fs.path(path))) then | |
return relativePathToDotPath(path) | |
end | |
end | |
function OnSetText(_uri, text) | |
-- Only evaluate requires if nevermore is used as a module loader. | |
if (not text:match('local require =.+(Nevermore)')) then return end | |
local hasRebuiltMapThisSession = false | |
local diffs = {} | |
for localPos, moduleName in text:gmatch('()local%s+[%w_]+%s=%srequire%("+([%w_]+)"%)') do | |
local relativeModuleDotPath = getLuaFile(moduleName) | |
if (not relativeModuleDotPath) and (not hasRebuiltMapThisSession) then | |
hasRebuiltMapThisSession = true | |
buildFileMap() | |
relativeModuleDotPath = getLuaFile(moduleName) | |
end | |
if (relativeModuleDotPath) then | |
diffs[#diffs + 1] = { | |
start = localPos, | |
finish = localPos - 1, | |
text = ("---@module %s\n"):format(relativeModuleDotPath), | |
} | |
end | |
end | |
if (#diffs == 0) then return end | |
return diffs | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment