Skip to content
This repository has been archived by the owner on Jun 19, 2024. It is now read-only.

[feat] Response body stored (only for JSON responses) #100

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
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
4 changes: 2 additions & 2 deletions .github/workflows/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v18
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- run: |
nix develop ./contrib -c make test
nix develop .#ci -c make test
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ have to leave Neovim!

## Notices

- **2023-07-12**: tagged 0.2 release before changes for 0.10 compatibility
- **2021-11-04**: HTTP Tree-Sitter parser now depends on JSON parser for the JSON bodies detection,
please install it too.
- **2021-08-26**: We have deleted the syntax file for HTTP files to start using the tree-sitter parser instead,
Expand Down Expand Up @@ -77,6 +78,9 @@ use {
result = {
-- toggle showing URL, HTTP info, headers at top the of result window
show_url = true,
-- show the generated curl command in case you want to launch
-- the same request via the terminal (can be verbose)
show_curl_command = false,
show_http_info = true,
show_headers = true,
-- executables or functions for formatting response body [optional]
Expand Down Expand Up @@ -149,6 +153,13 @@ request method (e.g. `GET`) and run `rest.nvim`.

---

### Debug


Run `export DEBUG_PLENARY="debug"` before starting nvim. Logs will appear most
likely in ~/.cache/nvim/rest.nvim.log


## Contribute

1. Fork it (https://github.com/rest-nvim/rest.nvim/fork)
Expand All @@ -162,6 +173,7 @@ test`.

## Related software

- [vim-rest-console](https://github.com/diepm/vim-rest-console)
- [Hurl](https://hurl.dev/)
- [HTTPie](https://httpie.io/)
- [httpYac](https://httpyac.github.io/)
Expand Down
20 changes: 20 additions & 0 deletions doc/rest-nvim.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ CONTENTS *rest-nvim-contents*
3. Import body from external file......|rest-nvim-usage-external-files|
4. Environment Variables........|rest-nvim-usage-environment-variables|
5. Dynamic Variables................|rest-nvim-usage-dynamic-variables|
6. Callbacks................................|rest-nvim-usage-callbacks|
5. Known issues..........................................|rest-nvim-issues|
6. License..............................................|rest-nvim-license|
7. Contributing....................................|rest-nvim-contributing|
Expand Down Expand Up @@ -119,6 +120,9 @@ COMMANDS *rest-nvim-usage-commands*
Same as `RestNvim` but it returns the cURL command without executing the
request. Intended for debugging purposes.

- `:RestLog`
Shows `rest.nvim` logs (export DEBUG_PLENARY=debug for more logs).

- `:RestSelectEnv path/to/env`
Set the path to an env file.

Expand Down Expand Up @@ -220,6 +224,22 @@ You can extend or overwrite built-in dynamic variables, with the config key
` },`
`})`

===============================================================================
CALLBACKS *rest-nvim-usage-callbacks*

rest.nvim fires different events upon requests:
- a User RestStartRequest event when launching the request
- a User RestStopRequest event when the requests finishes or errors out

vim.api.nvim_create_autocmd("User", {
pattern = "RestStartRequest",
once = true,
callback = function(opts)
print("IT STARTED")
vim.pretty_print(opts)
end,
})


===============================================================================
KNOWN ISSUES *rest-nvim-issues*
Expand Down
File renamed without changes.
72 changes: 28 additions & 44 deletions contrib/flake.nix → flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -13,49 +13,18 @@

mkDevShell = luaVersion:
let
# luaPkgs = pkgs."lua${luaVersion}".pkgs;
luaEnv = pkgs."lua${luaVersion}".withPackages (lp: with lp; [
busted
luacheck
luarocks
]);
neovimConfig = pkgs.neovimUtils.makeNeovimConfig {
plugins = with pkgs.vimPlugins; [
{
plugin = packer-nvim;
type = "lua";
config = ''
require('packer').init({
luarocks = {
python_cmd = 'python' -- Set the python command to use for running hererocks
},
})
-- require my own manual config
require('init-manual')
'';
}
{ plugin = (nvim-treesitter.withPlugins (
plugins: with plugins; [
tree-sitter-lua
tree-sitter-http
tree-sitter-json
]
));
}
{ plugin = plenary-nvim; }
];
customRC = "";
wrapRc = false;
};
myNeovim = pkgs.wrapNeovimUnstable pkgs.neovim-unwrapped neovimConfig;
in
pkgs.mkShell {
name = "rest-nvim";
buildInputs = [
pkgs.sumneko-lua-language-server
luaEnv
pkgs.stylua
myNeovim
# pkgs.neovim # assume user has one already installed
];

shellHook = let
Expand All @@ -67,30 +36,45 @@
tree-sitter-json
]
))];
# opt = map (x: x.plugin) pluginsPartitioned.right;
};
# };
packDirArgs.myNeovimPackages = myVimPackage;
in
''
cat <<-EOF > minimal.vim
set rtp+=.
set packpath^=${pkgs.vimUtils.packDir packDirArgs}
EOF
export DEBUG_PLENARY="debug"
cat <<-EOF > minimal.vim
set rtp+=.
set packpath^=${pkgs.vimUtils.packDir packDirArgs}
EOF
'';
};

in
{

# packages = {
# default = self.packages.${system}.luarocks-51;
# luarocks-51 = mkPackage "5_1";
# luarocks-52 = mkPackage "5_2";
# };

devShells = {
default = self.devShells.${system}.luajit;
ci = let
neovimConfig = pkgs.neovimUtils.makeNeovimConfig {
plugins = with pkgs.vimPlugins; [
{ plugin = (nvim-treesitter.withPlugins (
plugins: with plugins; [
tree-sitter-lua
tree-sitter-http
tree-sitter-json
]
));
}
{ plugin = plenary-nvim; }
];
customRC = "";
wrapRc = false;
};
myNeovim = pkgs.wrapNeovimUnstable pkgs.neovim-unwrapped neovimConfig;
in
(mkDevShell "jit").overrideAttrs(oa: {
buildInputs = oa.buildInputs ++ [ myNeovim ];
});

luajit = mkDevShell "jit";
lua-51 = mkDevShell "5_1";
lua-52 = mkDevShell "5_2";
Expand Down
1 change: 1 addition & 0 deletions ftplugin/http.vim
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
set commentstring=#\ %s
1 change: 1 addition & 0 deletions lua/rest-nvim/config/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ local config = {
timeout = 150,
},
result = {
show_curl_command = true,
show_url = true,
show_http_info = true,
show_headers = true,
Expand Down
85 changes: 54 additions & 31 deletions lua/rest-nvim/curl/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,22 @@ local function is_executable(x)
return false
end

local function format_curl_cmd(res)
local cmd = "curl"

for _, value in pairs(res) do
if string.sub(value, 1, 1) == "-" then
cmd = cmd .. " " .. value
else
cmd = cmd .. " '" .. value .. "'"
end
end

-- remote -D option
cmd = string.gsub(cmd, "-D '%S+' ", "")
return cmd
end

-- get_or_create_buf checks if there is already a buffer with the rest run results
-- and if the buffer does not exists, then create a new one
M.get_or_create_buf = function()
Expand All @@ -24,9 +40,9 @@ M.get_or_create_buf = function()
local existing_bufnr = vim.fn.bufnr(tmp_name)
if existing_bufnr ~= -1 then
-- Set modifiable
vim.api.nvim_buf_set_option(existing_bufnr, "modifiable", true)
vim.api.nvim_set_option_value("modifiable", true, { buf = existing_bufnr })
-- Prevent modified flag
vim.api.nvim_buf_set_option(existing_bufnr, "buftype", "nofile")
vim.api.nvim_set_option_value("buftype", "nofile", { buf = existing_bufnr })
-- Delete buffer content
vim.api.nvim_buf_set_lines(
existing_bufnr,
Expand All @@ -37,21 +53,21 @@ M.get_or_create_buf = function()
)

-- Make sure the filetype of the buffer is httpResult so it will be highlighted
vim.api.nvim_buf_set_option(existing_bufnr, "ft", "httpResult")
vim.api.nvim_set_option_value("ft", "httpResult", { buf = existing_bufnr })

return existing_bufnr
end

-- Create new buffer
local new_bufnr = vim.api.nvim_create_buf(false, "nomodeline")
local new_bufnr = vim.api.nvim_create_buf(false, true)
vim.api.nvim_buf_set_name(new_bufnr, tmp_name)
vim.api.nvim_buf_set_option(new_bufnr, "ft", "httpResult")
vim.api.nvim_buf_set_option(new_bufnr, "buftype", "nofile")
vim.api.nvim_set_option_value("ft", "httpResult", { buf = new_bufnr })
vim.api.nvim_set_option_value("buftype", "nofile", { buf = new_bufnr })

return new_bufnr
end

local function create_callback(method, url, script_str)
local function create_callback(curl_cmd, method, url, script_str, req_var)
return function(res)
if res.exit ~= 0 then
log.error("[rest.nvim] " .. utils.curl_error(res.exit))
Expand All @@ -63,7 +79,7 @@ local function create_callback(method, url, script_str)
-- get content type
for _, header in ipairs(res.headers) do
if string.lower(header):find("^content%-type") then
content_type = header:match("application/(%l+)") or header:match("text/(%l+)")
content_type = header:match("application/([-a-z]+)") or header:match("text/(%l+)")
break
end
end
Expand All @@ -83,6 +99,11 @@ local function create_callback(method, url, script_str)
end
end

-- This can be quite verbose so let user control it
if config.get("result").show_curl_command then
vim.api.nvim_buf_set_lines(res_bufnr, 0, 0, false, { "Command: " .. curl_cmd })
end

if config.get("result").show_url then
--- Add metadata into the created buffer (status code, date, etc)
-- Request statement (METHOD URL)
Expand Down Expand Up @@ -148,11 +169,24 @@ local function create_callback(method, url, script_str)
}, false, {})
end
end
-- check if the response is a json
-- parse the json response and store the data on memory
if content_type == "json" and req_var ~= "" then
local req_var_store = vim.api.nvim_get_var("req_var_store")
req_var_store[req_var] = vim.json.decode(res.body)
vim.api.nvim_set_var("req_var_store", req_var_store)
end

-- append response container
res.body = "#+RESPONSE\n" .. res.body .. "\n#+END"
local buf_content = "#+RESPONSE\n"
if utils.is_binary_content_type(content_type) then
buf_content = buf_content .. "Binary answer"
else
buf_content = buf_content .. res.body
end
buf_content = buf_content .. "\n#+END"

local lines = utils.split(res.body, "\n")
local lines = utils.split(buf_content, "\n")
local line_count = vim.api.nvim_buf_line_count(res_bufnr) - 1
vim.api.nvim_buf_set_lines(res_bufnr, line_count, line_count + #lines, false, lines)

Expand All @@ -167,7 +201,7 @@ local function create_callback(method, url, script_str)
end
vim.cmd(cmd_split .. res_bufnr)
-- Set unmodifiable state
vim.api.nvim_buf_set_option(res_bufnr, "modifiable", false)
vim.api.nvim_set_option_value("modifiable", false, { buf = res_bufnr })
end

-- Send cursor in response buffer to start
Expand All @@ -194,40 +228,29 @@ local function create_callback(method, url, script_str)
end
end

local function format_curl_cmd(res)
local cmd = "curl"

for _, value in pairs(res) do
if string.sub(value, 1, 1) == "-" then
cmd = cmd .. " " .. value
else
cmd = cmd .. " '" .. value .. "'"
end
end

-- remote -D option
cmd = string.gsub(cmd, "-D '%S+' ", "")
return cmd
end

-- curl_cmd runs curl with the passed options, gets or creates a new buffer
-- and then the results are printed to the recently obtained/created buffer
-- @param opts (table) curl arguments:
-- - yank_dry_run (boolean): displays the command
-- - arguments are forwarded to plenary
M.curl_cmd = function(opts)
if opts.dry_run then
local res = curl[opts.method](opts)
local curl_cmd = format_curl_cmd(res)
-- plenary's curl module is strange in the sense that with "dry_run" it returns the command
-- otherwise it starts the request :/
local dry_run_opts = vim.tbl_extend("force", opts, { dry_run = true })
local res = curl[opts.method](dry_run_opts)
local curl_cmd = format_curl_cmd(res)

if opts.dry_run then
if config.get("yank_dry_run") then
vim.cmd("let @+=" .. string.format("%q", curl_cmd))
end

vim.api.nvim_echo({ { "[rest.nvim] Request preview:\n", "Comment" }, { curl_cmd } }, false, {})
return
else
opts.callback = vim.schedule_wrap(create_callback(opts.method, opts.url, opts.script_str))
opts.callback = vim.schedule_wrap(
create_callback(curl_cmd, opts.method, opts.url, opts.script_str, opts.req_var)
)
curl[opts.method](opts)
end
end
Expand Down
Loading