From 133497cc1921ae1cd05bdaca8763da6a96e61426 Mon Sep 17 00:00:00 2001 From: Mitchell Hanberg Date: Fri, 23 Jun 2023 19:24:20 -0400 Subject: [PATCH] fix: handle formatting files with syntax errors --- lib/next_ls.ex | 6 +++++- test/next_ls_test.exs | 48 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/lib/next_ls.ex b/lib/next_ls.ex index 58724239..b7420735 100644 --- a/lib/next_ls.ex +++ b/lib/next_ls.ex @@ -101,7 +101,8 @@ defmodule NextLS do runtime = lsp.assigns.runtime with {:ok, {formatter, _}} <- Runtime.call(runtime, {Mix.Tasks.Format, :formatter_for_file, [".formatter.exs"]}), - {:ok, response} <- Runtime.call(runtime, {Kernel, :apply, [formatter, [Enum.join(document, "\n")]]}) do + {:ok, response} when is_binary(response) or is_list(response) <- + Runtime.call(runtime, {Kernel, :apply, [formatter, [Enum.join(document, "\n")]]}) do {:reply, [ %TextEdit{ @@ -125,6 +126,9 @@ defmodule NextLS do }) {:reply, nil, lsp} + + _ -> + {:reply, nil, lsp} end end diff --git a/test/next_ls_test.exs b/test/next_ls_test.exs index f8f6280c..9d19114a 100644 --- a/test/next_ls_test.exs +++ b/test/next_ls_test.exs @@ -250,4 +250,52 @@ defmodule NextLSTest do } ] end + + test "formatting gracefully handles files with syntax errors", %{client: client} do + assert :ok == + notify(client, %{ + method: "initialized", + jsonrpc: "2.0", + params: %{} + }) + + notify client, %{ + method: "textDocument/didOpen", + jsonrpc: "2.0", + params: %{ + textDocument: %{ + uri: "file://lib/foo/bar.ex", + languageId: "elixir", + version: 1, + text: """ + defmodule Foo.Bar do + def run() do + + + :ok + end + """ + } + } + } + + assert_notification "window/logMessage", %{"message" => "[NextLS] Runtime ready..."} + + request client, %{ + method: "textDocument/formatting", + id: 2, + jsonrpc: "2.0", + params: %{ + textDocument: %{ + uri: "file://lib/foo/bar.ex" + }, + options: %{ + insertSpaces: true, + tabSize: 2 + } + } + } + + assert_result 2, nil + end end