Skip to content

Commit 6a714fe

Browse files
committed
feat: add generate hash code and equals code action
1 parent 112bf1e commit 6a714fe

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

lua/java/api/generate.lua

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,4 +97,63 @@ function M.generate_to_string(params)
9797
.run()
9898
end
9999

100+
---@param params nvim.CodeActionParamsResponse
101+
function M.generate_hash_code_and_equals(params)
102+
local instance = require('java.utils.instance_factory')
103+
local get_error_handler = require('java.handlers.error')
104+
local ui = require('java.utils.ui')
105+
106+
runner(function()
107+
local jdtls = instance.jdtls_client()
108+
local status = jdtls:java_check_hash_code_equals_status(params.params)
109+
110+
if not status or not status.fields or #status.fields < 1 then
111+
local message = string.format(
112+
'The operation is not applicable to the type %s.',
113+
status.type
114+
)
115+
require('java-core.utils.notify').warn(message)
116+
return
117+
end
118+
119+
local regenerate = false
120+
121+
if status.existingMethods and #status.existingMethods > 0 then
122+
local prompt = string.format(
123+
'Methods %s already exists in the Class %s. Do you want to regenerate the implementation?',
124+
'Regenerate',
125+
'Cancel'
126+
)
127+
128+
local choice = ui.select(prompt, { 'Regenerate', 'Cancel' })
129+
130+
if choice == 'Regenerate' then
131+
regenerate = true
132+
end
133+
end
134+
135+
local fields = ui.multi_select(
136+
'Select the fields to include in the hashCode() and equals() methods.',
137+
status.fields,
138+
function(field)
139+
return field.name
140+
end
141+
)
142+
143+
if not fields or #fields < 1 then
144+
return
145+
end
146+
147+
local edit = jdtls:java_generate_hash_code_equals({
148+
context = params.params,
149+
fields = fields,
150+
regenerate = regenerate,
151+
})
152+
153+
vim.lsp.util.apply_workspace_edit(edit, 'utf-8')
154+
end)
155+
.catch(get_error_handler('Generating hash code failed'))
156+
.run()
157+
end
158+
100159
return M

lua/java/commands/init.lua

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,10 @@ M.handlers = {
125125
require('java.api.generate').generate_to_string(params)
126126
end,
127127

128+
[M.commands.HASHCODE_EQUALS_PROMPT] = function(_, params)
129+
require('java.api.generate').generate_hash_code_and_equals(params)
130+
end,
131+
128132
---@param is_full_build boolean
129133
[M.commands.COMPILE_WORKSPACE] = function(is_full_build)
130134
require('java.api.build').full_build_workspace(is_full_build)

0 commit comments

Comments
 (0)