Skip to content

Commit

Permalink
if not x, do: y => unless x, do: y
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust committed Jan 25, 2024
1 parent b01d328 commit 3c13f41
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
4 changes: 4 additions & 0 deletions lib/style/blocks.ex
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ defmodule Styler.Style.Blocks do
[{negator, _, [expr]}, [{do_, do_body}, {else_, else_body}]] when is_negator(negator) ->
zipper |> Zipper.replace({:if, m, [expr, [{do_, else_body}, {else_, do_body}]]}) |> run(ctx)

# if not x, do: y => unless x, do: y
[{negator, _, [expr]}, [do_block]] when is_negator(negator) ->
zipper |> Zipper.replace({:unless, m, [expr, [do_block]]}) |> run(ctx)

# drop `else: nil`
[head, [do_block, {_, {:__block__, _, [nil]}}]] ->
{:cont, Zipper.replace(zipper, {:if, m, [head, [do_block]]}), ctx}
Expand Down
12 changes: 5 additions & 7 deletions test/style/blocks_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,11 @@ defmodule Styler.Style.BlocksTest do
""")
end

test "if not => unless" do
assert_style("if not x, do: y", "unless x, do: y")
assert_style("if !x, do: y", "unless x, do: y")
end

test "Credo.Check.Refactor.UnlessWithElse" do
for negator <- ["!", "not "] do
assert_style(
Expand Down Expand Up @@ -826,15 +831,8 @@ defmodule Styler.Style.BlocksTest do

test "Credo.Check.Refactor.NegatedConditionsWithElse" do
for negator <- ["!", "not "] do
assert_style("if #{negator}foo, do: :bar")
assert_style("if #{negator}foo, do: :bar, else: :baz", "if foo, do: :baz, else: :bar")

assert_style("""
if #{negator}foo do
bar
end
""")

assert_style(
"""
if #{negator}foo do
Expand Down

0 comments on commit 3c13f41

Please sign in to comment.