Skip to content
Open
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
19 changes: 17 additions & 2 deletions lua/sops/api.lua
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,23 @@ function M.close()
return
end
local bufnr = fn.bufnr()
cmd.edit { args = { get_file_name():sub(8) } }
cmd.bwipeout { count = bufnr }
local file_name = get_file_name():sub(8)

if not vim.bo.modified then
cmd.edit { args = { file_name } }
cmd.bwipeout { count = bufnr }
return
end

sops.read_buffer_as_encrypted_file(file_name, bufnr, function(contents, code)
vim.bo[bufnr].modified = false
cmd.edit { bang = true, args = { file_name } }
api.nvim_buf_set_lines(fn.bufnr(), 0, -1, false, contents)
if code ~= 200 then
vim.bo.modified = true
end
cmd.bwipeout { bang = true, count = bufnr }
end)
end

function M.toggle()
Expand Down
44 changes: 44 additions & 0 deletions lua/sops/sops.lua
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
local config = require 'sops.config'
local notify = require 'sops.notify'
local utils = require 'sops.utils'

local M = {}

local function get_editor_path()
local Path = require 'plenary.path'
return Path:new(utils.get_script_path()):joinpath('../../editor.lua'):absolute()
end

local function get_temp_file(file)
local extension = file:match('(%.[^./\\]+)$') or ''
return vim.fn.tempname() .. extension
end

local function build_env(...)
local env = {}
local os_env = vim.loop.os_environ()
Expand Down Expand Up @@ -121,4 +132,37 @@ function M.read_encrypted_file(file, on_success, on_error)
return job
end

function M.read_buffer_as_encrypted_file(file, bufnr, on_success, on_error)
local temp_file = get_temp_file(file)
local editor = get_editor_path()

local copy_success, copy_error = vim.loop.fs_copyfile(file, temp_file)
if not copy_success then
notify.error('SOPS: Unable to copy encrypted file: ' .. vim.inspect(copy_error))
return nil
end

local job = M.call_sops {
args = { temp_file },
env = {
EDITOR = vim.v.progpath .. ' -l ' .. editor,
SOPS_NVIM_SOCKET = vim.v.servername,
SOPS_NVIM_BUFNR = bufnr,
},
success_codes = { 0, 200 },
on_success = function(ctx)
local encrypted_content = vim.fn.readfile(temp_file)
vim.fn.delete(temp_file)
on_success(encrypted_content, ctx.code)
end,
on_error = function(ctx)
vim.fn.delete(temp_file)
if on_error then
on_error(ctx.stderr)
end
end,
}
return job
end

return M