Skip to content

Commit ab77dcd

Browse files
committed
Add autocorrect for unless with else check
This autocorrects an unless with else check so that we're changing it to an `if` statement.
1 parent fb4be0e commit ab77dcd

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

lib/credo/check/refactor/unless_with_else.ex

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,23 @@ defmodule Credo.Check.Refactor.UnlessWithElse do
7171
line_no: line_no
7272
)
7373
end
74+
75+
def autocorrect(file, _issue) do
76+
{:ok, quoted} = :"Elixir.Code".string_to_quoted(file)
77+
78+
modified =
79+
quoted
80+
|> Macro.prewalk(&do_autocorrect/1)
81+
|> Macro.to_string()
82+
|> :"Elixir.Code".format_string!()
83+
|> to_string()
84+
85+
"#{modified}\n"
86+
end
87+
88+
defp do_autocorrect({:unless, meta, [clause, [do: falsy, else: truthy]]}) do
89+
{:if, meta, [clause, [do: truthy, else: falsy]]}
90+
end
91+
92+
defp do_autocorrect(ast), do: ast
7493
end

test/credo/check/refactor/unless_with_else_test.exs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,38 @@ defmodule Credo.Check.Refactor.UnlessWithElseTest do
4747
|> run_check(@described_check)
4848
|> assert_issue()
4949
end
50+
51+
describe "autocorrect/2" do
52+
test "changes the unless with else to an if clause" do
53+
starting = """
54+
defmodule CredoSampleModule do
55+
def some_function(parameter1, parameter2) do
56+
unless allowed? do
57+
unless other_condition? do
58+
something
59+
end
60+
else
61+
something_else
62+
end
63+
end
64+
end
65+
"""
66+
67+
expected = """
68+
defmodule CredoSampleModule do
69+
def some_function(parameter1, parameter2) do
70+
if allowed? do
71+
something_else
72+
else
73+
unless other_condition? do
74+
something
75+
end
76+
end
77+
end
78+
end
79+
"""
80+
81+
assert @described_check.autocorrect(starting, nil) == expected
82+
end
83+
end
5084
end

0 commit comments

Comments
 (0)