Skip to content

Commit 67c1923

Browse files
committed
Add input validation for switches
1 parent 5f38409 commit 67c1923

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

lua/neogit/lib/popup/builder.lua

+6
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ local M = {}
5454
---@field type string
5555
---@field user_input boolean
5656
---@field value string?
57+
---@field validate fun(string): boolean
58+
---@field validate_help string|nil
5759

5860
---@class PopupConfig
5961
---@field id string
@@ -252,6 +254,10 @@ function M:switch(key, cli, description, opts)
252254
internal = opts.internal,
253255
cli_prefix = opts.cli_prefix,
254256
user_input = opts.user_input,
257+
validate = opts.validate or function()
258+
return true
259+
end,
260+
validate_help = opts.validate_help,
255261
cli_suffix = opts.cli_suffix,
256262
options = opts.options,
257263
incompatible = util.build_reverse_lookup(opts.incompatible),

lua/neogit/lib/popup/init.lua

+11-2
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,17 @@ function M:toggle_switch(switch)
119119
if switch.user_input then
120120
if switch.enabled then
121121
local value = input.get_user_input(switch.cli_prefix .. switch.cli_base, { separator = "" })
122-
if value then
123-
switch.cli = switch.cli_base .. value
122+
if value and value ~= "" then
123+
if switch.validate(value) then
124+
switch.cli = switch.cli_base .. value
125+
else
126+
switch.enabled = false
127+
switch.cli = switch.cli_base
128+
notification.warn(switch.validate_help)
129+
end
130+
else
131+
switch.enabled = false
132+
switch.cli = switch.cli_base
124133
end
125134
else
126135
switch.cli = switch.cli_base

lua/neogit/popups/log/init.lua

+8-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,14 @@ function M.create()
1919
:option("F", "grep", "", "Search messages", { key_prefix = "-" })
2020
:switch("G", "G", "Search changes", { user_input = true, cli_prefix = "-" })
2121
:switch("S", "S", "Search occurrences", { user_input = true, cli_prefix = "-" })
22-
:switch("L", "L", "Trace line evolution", { user_input = true, cli_prefix = "-" })
22+
:switch("L", "L", "Trace line evolution", {
23+
user_input = true,
24+
cli_prefix = "-",
25+
validate_help = "Input must match 'start,end:file' or ':funcname:file'",
26+
validate = function(input)
27+
return (input:match("^%d+,%d+:.-$") ~= nil) or (input:match("^:.-:.-$") ~= nil)
28+
end,
29+
})
2330
:option("s", "since", "", "Limit to commits since", { key_prefix = "-" })
2431
:option("u", "until", "", "Limit to commits until", { key_prefix = "-" })
2532
:switch("m", "no-merges", "Omit merges", { key_prefix = "=" })

0 commit comments

Comments
 (0)