init.lua (1677B)
1 local gpg = { key = 0 } 2 3 local function splitext(file) 4 if file == nil then return nil, nil end 5 local i = file:reverse():find('%.') 6 if i == nil then return file, nil end 7 return file:sub(0, -(i + 1)), file:sub(-i) 8 end 9 10 local function errpipe(file, cmd, p) 11 local err, ostr, estr = vis:pipe(file, {start = 0, finish = file.size}, cmd) 12 if p == true and err ~= 0 and estr ~= nil then 13 vis:message(estr) 14 end 15 16 return err, ostr, estr 17 end 18 19 local function decrypt(file) 20 local f, e = splitext(file.name) 21 if e ~= '.gpg' then return end 22 23 local err, ostr, estr = errpipe(file, "gpg -d", false) 24 if err ~= 0 then return false end 25 26 local i = estr:find("ID") 27 local j = estr:find(",", i) 28 local keyid = estr:sub(i+3, j-1) 29 if keyid ~= gpg.key then 30 vis:info(estr:gsub("\n[ ]*", " ")) 31 gpg.key = keyid 32 end 33 34 file:delete(0, file.size) 35 file:insert(0, ostr) 36 file.modified = false 37 return true 38 end 39 vis.events.subscribe(vis.events.FILE_OPEN, decrypt) 40 vis.events.subscribe(vis.events.FILE_SAVE_POST, decrypt) 41 42 local function encrypt(file) 43 local f, e = splitext(file.name) 44 if e ~= '.gpg' then return end 45 46 if gpg.key == 0 then 47 vis:info('encrypt: keyid not found. file not saved.') 48 return false 49 end 50 51 local tfn = os.tmpname() 52 local cmd = "gpg --yes -o " .. tfn .. " -e -r " .. gpg.key 53 local err = errpipe(file, cmd, true) 54 if err ~= 0 then return false end 55 56 local tf = io.open(tfn, 'rb') 57 file:delete(0, file.size) 58 file:insert(0, tf:read("*a")) 59 tf:close() 60 os.remove(tfn) 61 62 return true 63 end 64 vis.events.subscribe(vis.events.FILE_SAVE_PRE, encrypt) 65 66 vis:command_register("gpg-key", function() 67 vis:info("gpg-key: " .. gpg.key) 68 end, "Echo the currently set key ID") 69 70 return gpg