-
-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: alias-refactor workspace command (#386)
Adds an alias refactor workspace command to Next LS. Your cursor should be at the target module that you wish to alias. It will insert the alias at the of the nearest defmodule definition scoping the refactor only to the current module instead of the whole file.
- Loading branch information
Showing
9 changed files
with
758 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
defmodule NextLS.Commands do | ||
@moduledoc false | ||
|
||
@labels %{ | ||
"from-pipe" => "Inlined pipe", | ||
"to-pipe" => "Extracted to a pipe", | ||
"alias-refactor" => "Refactored with an alias" | ||
} | ||
@doc "Creates a label for the workspace apply struct from the command name" | ||
def label(command) when is_map_key(@labels, command), do: @labels[command] | ||
|
||
def label(command) do | ||
raise ArgumentError, "command #{inspect(command)} not supported" | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
defmodule NextLS.Commands.Alias do | ||
@moduledoc """ | ||
Refactors a module with fully qualified calls to an alias. | ||
The cursor position should be under the module name that you wish to alias. | ||
""" | ||
import Schematic | ||
|
||
alias GenLSP.Enumerations.ErrorCodes | ||
alias GenLSP.Structures.Position | ||
alias GenLSP.Structures.Range | ||
alias GenLSP.Structures.TextEdit | ||
alias GenLSP.Structures.WorkspaceEdit | ||
alias NextLS.ASTHelpers | ||
alias NextLS.EditHelpers | ||
alias Sourceror.Zipper, as: Z | ||
|
||
@line_length 121 | ||
|
||
defp opts do | ||
map(%{ | ||
position: Position.schematic(), | ||
uri: str(), | ||
text: list(str()) | ||
}) | ||
end | ||
|
||
def run(opts) do | ||
with {:ok, %{text: text, uri: uri, position: position}} <- unify(opts(), Map.new(opts)), | ||
{:ok, ast, comments} = parse(text), | ||
{:ok, defm} <- ASTHelpers.get_surrounding_module(ast, position), | ||
{:ok, {:__aliases__, _, modules}} <- get_node(ast, position) do | ||
range = make_range(defm) | ||
indent = EditHelpers.get_indent(text, range.start.line) | ||
aliased = get_aliased(defm, modules) | ||
|
||
comments = | ||
Enum.filter(comments, fn comment -> | ||
comment.line > range.start.line && comment.line <= range.end.line | ||
end) | ||
|
||
to_algebra_opts = [comments: comments] | ||
doc = Code.quoted_to_algebra(aliased, to_algebra_opts) | ||
formatted = doc |> Inspect.Algebra.format(@line_length) |> IO.iodata_to_binary() | ||
|
||
%WorkspaceEdit{ | ||
changes: %{ | ||
uri => [ | ||
%TextEdit{ | ||
new_text: | ||
EditHelpers.add_indent_to_edit( | ||
formatted, | ||
indent | ||
), | ||
range: range | ||
} | ||
] | ||
} | ||
} | ||
else | ||
{:error, message} -> | ||
%GenLSP.ErrorResponse{code: ErrorCodes.parse_error(), message: inspect(message)} | ||
end | ||
end | ||
|
||
defp parse(lines) do | ||
lines | ||
|> Enum.join("\n") | ||
|> Spitfire.parse_with_comments(literal_encoder: &{:ok, {:__block__, &2, [&1]}}) | ||
|> case do | ||
{:error, ast, comments, _errors} -> | ||
{:ok, ast, comments} | ||
|
||
other -> | ||
other | ||
end | ||
end | ||
|
||
defp make_range(original_ast) do | ||
range = Sourceror.get_range(original_ast) | ||
|
||
%Range{ | ||
start: %Position{line: range.start[:line] - 1, character: range.start[:column] - 1}, | ||
end: %Position{line: range.end[:line] - 1, character: range.end[:column] - 1} | ||
} | ||
end | ||
|
||
def get_node(ast, pos) do | ||
pos = [line: pos.line + 1, column: pos.character + 1] | ||
|
||
result = | ||
ast | ||
|> Z.zip() | ||
|> Z.traverse(nil, fn tree, acc -> | ||
node = Z.node(tree) | ||
range = Sourceror.get_range(node) | ||
|
||
if not is_nil(range) and | ||
match?({:__aliases__, _context, _modules}, node) && | ||
Sourceror.compare_positions(range.start, pos) in [:lt, :eq] && | ||
Sourceror.compare_positions(range.end, pos) in [:gt, :eq] do | ||
{tree, node} | ||
else | ||
{tree, acc} | ||
end | ||
end) | ||
|
||
case result do | ||
{_, nil} -> | ||
{:error, "could not find a module to alias at the cursor position"} | ||
|
||
{_, {_t, _m, []}} -> | ||
{:error, "could not find a module to alias at the cursor position"} | ||
|
||
{_, {_t, _m, [_argument | _rest]} = node} -> | ||
{:ok, node} | ||
end | ||
end | ||
|
||
defp get_aliased(defm, modules) do | ||
last = List.last(modules) | ||
|
||
replaced = | ||
Macro.prewalk(defm, fn | ||
{:__aliases__, context, ^modules} -> {:__aliases__, context, [last]} | ||
ast -> ast | ||
end) | ||
|
||
alias_to_add = {:alias, [alias: false], [{:__aliases__, [], modules}]} | ||
|
||
{:defmodule, context, [module, [{do_block, block}]]} = replaced | ||
|
||
case block do | ||
{:__block__, block_context, defs} -> | ||
{:defmodule, context, [module, [{do_block, {:__block__, block_context, [alias_to_add | defs]}}]]} | ||
|
||
{_, _, _} = original -> | ||
{:defmodule, context, [module, [{do_block, {:__block__, [], [alias_to_add, original]}}]]} | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
defmodule NextLS.AliasTest do | ||
use ExUnit.Case, async: true | ||
|
||
import GenLSP.Test | ||
import NextLS.Support.Utils | ||
|
||
@moduletag :tmp_dir | ||
@moduletag root_paths: ["my_proj"] | ||
|
||
setup %{tmp_dir: tmp_dir} do | ||
File.mkdir_p!(Path.join(tmp_dir, "my_proj/lib")) | ||
File.write!(Path.join(tmp_dir, "my_proj/mix.exs"), mix_exs()) | ||
|
||
cwd = Path.join(tmp_dir, "my_proj") | ||
|
||
foo_path = Path.join(cwd, "lib/foo.ex") | ||
|
||
foo = """ | ||
defmodule Foo do | ||
def to_list() do | ||
Foo.Bar.to_list(Map.new()) | ||
end | ||
def to_map() do | ||
Foo.Bar.to_map(List.new()) | ||
end | ||
end | ||
""" | ||
|
||
File.write!(foo_path, foo) | ||
|
||
[foo: foo, foo_path: foo_path] | ||
end | ||
|
||
setup :with_lsp | ||
|
||
setup context do | ||
assert :ok == notify(context.client, %{method: "initialized", jsonrpc: "2.0", params: %{}}) | ||
assert_is_ready(context, "my_proj") | ||
assert_compiled(context, "my_proj") | ||
assert_notification "$/progress", %{"value" => %{"kind" => "end", "message" => "Finished indexing!"}} | ||
|
||
did_open(context.client, context.foo_path, context.foo) | ||
context | ||
end | ||
|
||
test "refactors with alias", %{client: client, foo_path: foo} do | ||
foo_uri = uri(foo) | ||
id = 1 | ||
|
||
request client, %{ | ||
method: "workspace/executeCommand", | ||
id: id, | ||
jsonrpc: "2.0", | ||
params: %{ | ||
command: "alias-refactor", | ||
arguments: [%{uri: foo_uri, position: %{line: 2, character: 8}}] | ||
} | ||
} | ||
|
||
expected_edit = | ||
String.trim(""" | ||
defmodule Foo do | ||
alias Foo.Bar | ||
def to_list() do | ||
Bar.to_list(Map.new()) | ||
end | ||
def to_map() do | ||
Bar.to_map(List.new()) | ||
end | ||
end | ||
""") | ||
|
||
assert_request(client, "workspace/applyEdit", 500, fn params -> | ||
assert %{"edit" => edit, "label" => "Refactored with an alias"} = params | ||
|
||
assert %{ | ||
"changes" => %{ | ||
^foo_uri => [%{"newText" => text, "range" => range}] | ||
} | ||
} = edit | ||
|
||
assert text == expected_edit | ||
|
||
assert range["start"] == %{"character" => 0, "line" => 0} | ||
assert range["end"] == %{"character" => 3, "line" => 8} | ||
end) | ||
end | ||
end |
Oops, something went wrong.