refactor: filename validation

remotes/origin/HEAD
pseudometa 2023-03-27 12:43:42 +02:00
parent 749027d470
commit b6056e5dee
1 changed files with 15 additions and 15 deletions

View File

@ -54,22 +54,22 @@ local function fileOp(op)
-- selene: allow(high_cyclomatic_complexity) -- selene: allow(high_cyclomatic_complexity)
-- INFO completion = "dir" allows for completion via cmp-omni -- INFO completion = "dir" allows for completion via cmp-omni
vim.ui.input({ prompt = promptStr, default = prefill, completion = "dir" }, function(newName) vim.ui.input({ prompt = promptStr, default = prefill, completion = "dir" }, function(newName)
-- validation -- VALIDATION OF FILENAME
local invalidName = false if not newName then return end -- input has been cancelled
local sameName
if newName then local invalidName = newName:find("^%s+$")
invalidName = newName:find("^%s*$")
or newName:find("[\\:]") or newName:find("[\\:]")
or newName:find("/$") or newName:find("/$")
or (newName:find("^/") and not op == "move-rename") or (newName:find("^/") and not op == "move-rename")
sameName = newName == oldName local sameName = newName == oldName
end local emptyInput = newName == ""
if not newName or invalidName or sameName then -- cancel
if invalidName or sameName or emptyInput then
if op == "newFromSel" then if op == "newFromSel" then
cmd.undo() -- undo deletion cmd.undo() -- undo deletion
fn.setreg("z", prevReg) -- restore register content fn.setreg("z", prevReg) -- restore register content
end end
if invalidName then if invalidName or emptyInput then
vim.notify("Invalid filename.", logError) vim.notify("Invalid filename.", logError)
elseif sameName then elseif sameName then
vim.notify("Cannot use the same filename.", logError) vim.notify("Cannot use the same filename.", logError)
@ -77,12 +77,11 @@ local function fileOp(op)
return return
end end
-- create folders if necessary -- DETERMINE PATH AND EXTENSION
-- TODO upon release of neovim 0.9, use `:write ++p` https://twitter.com/Neovim/status/1589469857388834816?s=20&t=KNpSU7IESQAAWQwG04OjTQ
local hasPath = newName:find("/") local hasPath = newName:find("/")
if hasPath then if hasPath then
local newFolder = newName:gsub("/.-$", "") local newFolder = newName:gsub("/.-$", "")
fn.mkdir(newFolder, "p") fn.mkdir(newFolder, "p") -- create folders if necessary
end end
local extProvided = newName:find(".%.[^/]*$") -- non-leading dot to not include dotfiles without extension local extProvided = newName:find(".%.[^/]*$") -- non-leading dot to not include dotfiles without extension
@ -94,6 +93,7 @@ local function fileOp(op)
return return
end end
-- EXECUTE FILE OPERATION
cmd.update() -- save current file; needed for users with `hidden=false` cmd.update() -- save current file; needed for users with `hidden=false`
if op == "duplicate" then if op == "duplicate" then
cmd.saveas(newFilePath) cmd.saveas(newFilePath)