Skip to content

Instantly share code, notes, and snippets.

@oessessnex
Created May 15, 2022 22:31
Show Gist options
  • Save oessessnex/d63ebe89380abff5a3ee70d6e76e4ec8 to your computer and use it in GitHub Desktop.
Save oessessnex/d63ebe89380abff5a3ee70d6e76e4ec8 to your computer and use it in GitHub Desktop.
local M = {}
local uv = vim.loop
local fn = vim.fn
local api = vim.api
function password()
fn.inputsave()
local user = fn.expand("$USER")
local pw = fn.inputsecret(string.format("password for %s: ", user))
fn.inputrestore()
return pw
end
function test(pw, k)
local stdin = uv.new_pipe()
uv.spawn("sudo", {
args = {"-S", "-k", "true"},
stdio = {stdin, nil, nil}
}, k)
stdin:write(pw)
stdin:write("\n")
stdin:shutdown()
end
function write(pw, buf, lines, k)
local stdin = uv.new_pipe()
uv.spawn("sudo", {
args = {"-S", "-k", "tee", buf},
stdio = {stdin, nil, nil}
}, k)
stdin:write(pw)
stdin:write("\n")
local last = table.remove(lines)
for _, line in ipairs(lines) do
stdin:write(line)
stdin:write("\n")
end
stdin:write(last)
stdin:shutdown()
end
function M.sudowrite()
local pw = password()
local buf = api.nvim_buf_get_name(0)
local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false)
local function exitWrite(code, _)
if code == 0 then
vim.schedule(function()
api.nvim_echo({{string.format('"%s" written', buf), "Normal"}}, true, {})
api.nvim_buf_set_option(0, "modified", false)
end)
end
end
local function exitTest(code, _)
if code == 0 then
write(pw, buf, lines, exitWrite)
else
vim.schedule(function()
api.nvim_echo({{"incorrect password", "ErrorMsg"}}, true, {})
end)
end
end
test(pw, exitTest)
end
return M
@RayZ0rr
Copy link

RayZ0rr commented May 16, 2022

Do we call this function like (assuming sudowrite.lua is in autoload or plugin folder):
:lua sudowrite.sudowrite()

@brokenpylons
Copy link

@RayZ0rr You can put the file in the lua folder and call it with :lua require("sudowrite").sudowrite().

@Animeshz
Copy link

For some reason the bufnr is undefined (nil) for me... Any guesses, what's wrong?

@Animeshz
Copy link

Ohkey, adding up local bufnr = api.nvim_get_current_buf() fixes that, but still the file seems like its saved, but its content doesn't seem to be changed 🤔

E.g.

c20-05-22-09h35m18s

Unsaved mark (circle) has been changed to cross (X) on top bar of nvim, yet still the contents are as if they were before 👀

@Animeshz
Copy link

{ printf '%s\n' '1111' 'hi'; } | sudo -S -k tee /etc/randomfilename.txt

Even if I run this on terminal, the output comes out to be Enter Password or Place finger on fingerprint reader: User defined signal 1.

Can you please tell your sudo, neovim and tee's version?

@Animeshz
Copy link

Oops seems like it was issue from side of pam-fprint-grosshack, I'll check if anything there is preventing from using sudo -S. Thanks for the script, its working :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment