diff --git a/lib/ex_factor/changer.ex b/lib/ex_factor/changer.ex index 8e2736d..8a14b9c 100644 --- a/lib/ex_factor/changer.ex +++ b/lib/ex_factor/changer.ex @@ -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 @@ -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 @@ -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 diff --git a/test/ex_factor/changer_test.exs b/test/ex_factor/changer_test.exs index b187533..68ac9b6 100644 --- a/test/ex_factor/changer_test.exs +++ b/test/ex_factor/changer_test.exs @@ -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 """ @@ -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