-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathhandlers.lua
More file actions
104 lines (89 loc) · 2.59 KB
/
handlers.lua
File metadata and controls
104 lines (89 loc) · 2.59 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
local M = {}
local registry = require('opencode.registry')
local handler_group_modules = {
'opencode.commands.handlers.window',
'opencode.commands.handlers.agent',
'opencode.commands.handlers.workflow',
'opencode.commands.handlers.session',
'opencode.commands.handlers.diff',
'opencode.commands.handlers.permission',
}
---@return OpencodeCommandHandlerMap
local function get_handlers()
local all_handlers = {}
local handler_sources = {}
for _, module_name in ipairs(handler_group_modules) do
local module_exports = require(module_name)
local module_handlers = module_exports.handlers or module_exports
for handler_id, handler in pairs(module_handlers) do
if handler_sources[handler_id] then
error(
string.format(
"Duplicate handler_id '%s' in modules '%s' and '%s'",
handler_id,
handler_sources[handler_id],
module_name
)
)
end
handler_sources[handler_id] = module_name
all_handlers[handler_id] = handler
end
end
for handler_id, handler in pairs(registry.get_handlers()) do
if handler_sources[handler_id] then
error(
string.format(
"Duplicate handler_id '%s' in modules '%s' and extension registry",
handler_id,
handler_sources[handler_id]
)
)
end
handler_sources[handler_id] = 'extension registry'
all_handlers[handler_id] = handler
end
return all_handlers
end
-- Validate handler graph during module load for fast-fail behavior.
get_handlers()
---@param handler_id string
---@return OpencodeCommandHandler|nil
function M.get(handler_id)
return get_handlers()[handler_id]
end
---@return string[]
function M.ids()
local ids = vim.tbl_keys(get_handlers())
table.sort(ids)
return ids
end
---@param handler_id string
---@param api OpencodeCommandApi
---@param args string[]
---@param range? OpencodeSelectionRange
---@return boolean, any, OpencodeCommandDispatchError|nil
function M.execute(handler_id, api, args, range)
local handler = M.get(handler_id)
if not handler then
return false, nil, nil
end
local ok, result = pcall(handler, api, args or {}, range)
if ok then
return true, result, nil
end
if type(result) == 'table' and type(result.code) == 'string' and type(result.message) == 'string' then
if not result.handler_id then
result.handler_id = handler_id
end
return true, nil, result
end
return true,
nil,
{
code = 'handler_exception',
message = 'Command handler failed: ' .. handler_id,
handler_id = handler_id,
}
end
return M