Skip to content

Commit

Permalink
Rewrite case true/false to if else (`Credo.Check.Refactor.CaseTrivial…
Browse files Browse the repository at this point in the history
…Matches`)
  • Loading branch information
novaugust committed May 9, 2023
1 parent a902ae0 commit b2f6363
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/style/simple.ex
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,37 @@ defmodule Styler.Style.Simple do
{:cont, Zipper.replace(zipper, {reverse, r_meta, [lhs, rhs]}), ctx}
end

def run(
{{:case, _,
[
head,
[{_, [{:->, _, [[{:__block__, _, [true]}], true_body]}, {:->, _, [[{:__block__, _, [false]}], false_body]}]}]
]}, _} = zipper,
ctx
) do
{:cont, Zipper.replace(zipper, if_ast(head, true_body, false_body)), ctx}
end

def run(
{{:case, _,
[
head,
[{_, [{:->, _, [[{:__block__, _, [false]}], false_body]}, {:->, _, [[{:__block__, _, [true]}], true_body]}]}]
]}, _} = zipper,
ctx
) do
{:cont, Zipper.replace(zipper, if_ast(head, true_body, false_body)), ctx}
end

def run(zipper, ctx), do: {:cont, zipper, ctx}

# don't write an else clause if it's `false -> nil`
defp if_ast(head, true_body, {:__block__, _, [nil]}),
do: {:if, [do: []], [head, [{{:__block__, [], [:do]}, true_body}]]}

defp if_ast(head, true_body, false_body),
do: {:if, [do: [], end: []], [head, [{{:__block__, [], [:do]}, true_body}, {{:__block__, [], [:else]}, false_body}]]}

defp delimit(token), do: token |> String.to_charlist() |> remove_underscores([]) |> add_underscores([])

defp remove_underscores([?_ | rest], acc), do: remove_underscores(rest, acc)
Expand Down
69 changes: 69 additions & 0 deletions test/style/simple_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,73 @@ defmodule Styler.Style.SimpleTest do
assert_style("Enum.reverse(foo, bar) ++ bar")
end
end

describe "case true false do" do
test "rewrites case true false to if else" do
assert_style(
"""
case foo do
true -> :ok
false -> :error
end
""",
"""
if foo do
:ok
else
:error
end
"""
)

assert_style(
"""
case foo do
false -> :error
true -> :ok
end
""",
"""
if foo do
:ok
else
:error
end
"""
)

assert_style(
"""
case foo do
true -> :ok
false -> nil
end
""",
"""
if foo do
:ok
end
"""
)

assert_style(
"""
case foo do
true -> :ok
false ->
Logger.warn("it's false")
nil
end
""",
"""
if foo do
:ok
else
Logger.warn("it's false")
nil
end
"""
)
end
end
end

0 comments on commit b2f6363

Please sign in to comment.