Skip to content

Commit

Permalink
match better in changer
Browse files Browse the repository at this point in the history
  • Loading branch information
ckoch-cars committed Sep 20, 2021
1 parent c33f268 commit 5e428ed
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
11 changes: 8 additions & 3 deletions lib/ex_factor/changer.ex
Expand Up @@ -67,7 +67,7 @@ defmodule ExFactor.Changer do
end

defp find_alias_as(list, module) do
aalias = Enum.find(list, "", fn el -> el =~ "alias #{Util.module_to_string(module)}" end)
aalias = Enum.find(list, "", fn el -> match_alias?(el, module) end)

if String.match?(aalias, ~r/, as: /) do
aalias
Expand Down Expand Up @@ -134,12 +134,13 @@ defmodule ExFactor.Changer do
target_module = Keyword.fetch!(opts, :target_module)
target_string = Util.module_to_string(target_module)

if Enum.find(contents_list, fn el -> el =~ "alias #{target_string}" end) do
if Enum.find(contents_list, fn el -> match_alias?(el, target_string) end) do
{state, contents_list}
else
contents_list
|> Enum.reduce([], fn elem, acc ->
if elem =~ "alias #{source_string}" do
if match_alias?(elem, source_string) do
# if String.match?(elem, ~r/alias #{source_string}(\s|$|\,)/) do
new_alias = String.replace(elem, source_string, target_string)
[new_alias | [elem | acc]]
else
Expand All @@ -150,4 +151,8 @@ defmodule ExFactor.Changer do
|> then(fn list -> {state, list} end)
end
end

defp match_alias?(string, module_string) do
String.match?(string, ~r/alias #{module_string}(\s|$|\,)/)
end
end
7 changes: 7 additions & 0 deletions test/ex_factor/changer_test.exs
Expand Up @@ -30,9 +30,11 @@ defmodule ExFactor.ChangerTest do
content = """
defmodule ExFactor.Tmp.CallerModule do
alias ExFactor.Tmp.SourceMod
alias ExFactor.Tmp.SourceMod.Other
def pub1(arg_a) do
SourceMod.refactor1(arg_a)
end
def pub2(), do: Other
end
"""

Expand All @@ -49,9 +51,14 @@ defmodule ExFactor.ChangerTest do

caller = File.read!("lib/ex_factor/tmp/caller_module.ex")
assert caller =~ "alias ExFactor.Tmp.TargetModule"
# ensure we don't match dumbly
assert caller =~ "alias ExFactor.Tmp.SourceMod.Other"
refute caller =~ "alias ExFactor.Tmp.TargetModule.Other"
assert caller =~ "TargetModule.refactor1(arg_a)"
end

# update the annoying alias style: alias Foo.{Bar, Baz, Biz}

test "only add alias entry if it's missing" do
content = """
defmodule ExFactor.Tmp.SourceMod do
Expand Down

0 comments on commit 5e428ed

Please sign in to comment.