Skip to content

Commit

Permalink
Add extract function as an execute command
Browse files Browse the repository at this point in the history
  • Loading branch information
robmckinnon committed May 3, 2023
1 parent fae8f09 commit 1e69ee4
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
defmodule ElixirLS.LanguageServer.Experimental.CodeMod.RefactorExtractFunction do
alias ElixirLS.LanguageServer.Experimental.CodeMod.Diff
alias ElixirLS.LanguageServer.Experimental.CodeMod.ExtractFunction

alias Sourceror.Zipper

require Logger

def text_edits(original_text, tree, start_line, end_line, new_function_name) do
result =
tree
|> Zipper.zip()
|> ExtractFunction.extract_function(start_line + 1, end_line + 1, new_function_name)
|> Sourceror.to_string()

{:ok, Diff.diff(original_text, result)}
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ defmodule ElixirLS.LanguageServer.Providers.ExecuteCommand do
@handlers %{
"spec" => ExecuteCommand.ApplySpec,
"expandMacro" => ExecuteCommand.ExpandMacro,
"extractFunction" => ExecuteCommand.ExtractFunction,
"manipulatePipes" => ExecuteCommand.ManipulatePipes,
"restart" => ExecuteCommand.Restart,
"mixClean" => ExecuteCommand.MixClean,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
defmodule ElixirLS.LanguageServer.Providers.ExecuteCommand.ExtractFunction do
@moduledoc """
This module implements a custom command extract function.
Sends applyEdit request.
"""

alias ElixirLS.LanguageServer.JsonRpc
alias ElixirLS.LanguageServer.Server
alias ElixirLS.LanguageServer.Experimental.CodeMod.Ast
alias ElixirLS.LanguageServer.Experimental.CodeMod.RefactorExtractFunction

require Logger

@behaviour ElixirLS.LanguageServer.Providers.ExecuteCommand

@impl ElixirLS.LanguageServer.Providers.ExecuteCommand
def execute([uri, start_line, end_line, new_function_name], state) do
with source_file <- Server.get_source_file(state, uri),
{:ok, tree} <- Ast.from(source_file.text, include_comments: true),
{:ok, text_edits} <-
RefactorExtractFunction.text_edits(
source_file.text,
tree,
start_line,
end_line,
new_function_name
) do
apply_edits(uri, text_edits)
{:ok, nil}
end
end

def apply_edits(uri, text_edits) do
JsonRpc.send_request("workspace/applyEdit", %{
"label" => "Extract function",
"edit" => %{"changes" => %{uri => text_edits}}
}) |> IO.inspect(label: :rpc_response, limit: :infinity)
end
end

0 comments on commit 1e69ee4

Please sign in to comment.