Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add completions for sudo #273

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions nature/completions.lua → nature/completions/init.lua
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
local fs = require 'fs'

-- explanation: this specific function gives to us info about
-- the currently running source. this includes a path to the
-- source file (info.source)
-- we will use that to automatically load all commands by reading
-- all the files in this dir and just requiring it.
local info = debug.getinfo(1)
local commandDir = fs.dir(info.source)
if commandDir == '.' then return end

local commands = fs.readdir(commandDir)
for _, command in ipairs(commands) do
local name = command:gsub('%.lua', '') -- chop off extension
if name ~= 'init' then
-- skip this file (for obvious reasons)
require('nature.completions.' .. name)
end
end

function hilbish.completion.handler(line, pos)
if type(line) ~= 'string' then error '#1 must be a string' end
if type(pos) ~= 'number' then error '#2 must be a number' end
Expand Down
53 changes: 53 additions & 0 deletions nature/completions/sudo.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
local function curry(f)
return function (x) return function (y) return f(x,y) end end
end

local flags = {}
local function flag(f, description)
flags[f] = {description}
end

local addflag = curry(flag)

addflag '-A' 'Ask for password via askpass or $SUDO_ASKPASS'
addflag '-B' 'Ring the bell as part of the password prompt.'

hilbish.complete('command.sudo', function(query, ctx, fields)
table.remove(fields, 1)
local nonflags = table.filter(fields, function(v)
if v == '' then
return false
end
return v:match '^%-' == nil
end)

if #fields == 1 or #nonflags == 0 then
-- complete commands or sudo flags
if query:match ('^%-') then
local compFlags = {}
for flg, flgstuff in pairs(flags) do
if flg:match('^' .. query) then
compFlags[flg] = flgstuff
end
end

local compGroup = {
items = compFlags,
type = 'list'
}

return {compGroup}, query
end

local comps, pfx = hilbish.completion.bins(query, ctx, fields)
local compGroup = {
items = comps,
type = 'grid'
}

return {compGroup}, pfx
end

-- otherwise, get command flags
return hilbish.completion.call('command.' .. fields[2], query, ctx, fields)
end)
Loading