summaryrefslogtreecommitdiff
path: root/script/core/modifyRequirePath.lua
blob: 91c600acbbae0064067ac111f63ee5e34e12cc10 (plain)
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
local files  = require 'files'
local await  = require 'await'
local guide  = require 'parser.guide'
local rpath  = require 'workspace.require-path'
local furi   = require 'file-uri'
local util   = require 'utility'
local client = require 'client'
local lang   = require 'language'

---@alias rename { oldUri: uri, newUri: uri }

---@param changes table[]
---@param uri uri
---@param renames rename[]
local function checkConvert(changes, uri, renames)
    local state = files.getState(uri)
    if not state then
        return
    end

    guide.eachSpecialOf(state.ast, 'require', function (source)
        local call = source.parent
        if call.type ~= 'call' then
            return
        end
        local nameObj = call.args and call.args[1]
        if not nameObj then
            return
        end
        local name = nameObj.type == 'string' and nameObj[1]
        if type(name) ~= 'string' then
            return
        end
        local uris = rpath.findUrisByRequireName(uri, name)
        local ruri = uris and uris[1]
        if not ruri then
            return
        end
        for _, rename in ipairs(renames) do
            if rename.oldUri == ruri then
                local visibles = rpath.getVisiblePath(uri, furi.decode(rename.newUri))
                if #visibles > 0 then
                    local newName = visibles[1].name
                    changes[#changes+1] = {
                        uri    = uri,
                        start  = nameObj.start,
                        finish = nameObj.finish,
                        text   = util.viewString(newName, nameObj[2]),
                    }
                    return
                end
            end
        end
    end)
end

---@async
---@param renames rename[]
return function (renames)
    if #renames == 0 then
        return
    end
    local changes = {}
    for uri in files.eachFile() do
        checkConvert(changes, uri, renames)
        await.delay()
    end
    if #changes == 0 then
        return
    end

    local _, index = client.awaitRequestMessage('Info', lang.script.WINDOW_MODIFY_REQUIRE_PATH, {
        lang.script.WINDOW_MODIFY_REQUIRE_OK
    })

    if index == 1 then
        client.editMultiText(changes)
    end
end