Skip to content

Commit

Permalink
replace with statements with no arrows. closes #174
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust committed Jul 15, 2024
1 parent aee6e71 commit 0df8bc8
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 9 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ they can and will change without that change being reflected in Styler's semanti

### Fixes

* rewrite `with` with no left arrows to be normal code (#174)
* fix `with` arrow replacement + redundant body removal creating invalid statements (#184, h/t @JesseHerrick)
* allow Kernel unary `!` and `not` as valid pipe starts (#183, h/t @nherzing)

Expand Down
5 changes: 4 additions & 1 deletion lib/style/blocks.ex
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ defmodule Styler.Style.Blocks do
# Credo.Check.Refactor.WithClauses
def run({{:with, with_meta, children}, _} = zipper, ctx) when is_list(children) do
# a std lib `with` block will have at least one left arrow and a `do` body. anything else we skip ¯\_(ツ)_/¯
if Enum.any?(children, &left_arrow?/1) and Enum.any?(children, &match?([{{:__block__, _, [:do]}, _body} | _], &1)) do
arrow_or_match? = &(left_arrow?(&1) || match?({:=, _, _}, &1))
do_block? = &match?([{{:__block__, _, [:do]}, _body} | _], &1)

if Enum.any?(children, arrow_or_match?) and Enum.any?(children, do_block?) do
{preroll, children} =
children
|> Enum.map(fn
Expand Down
25 changes: 17 additions & 8 deletions test/style/blocks_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,21 @@ defmodule Styler.Style.BlocksTest do
x(y, z)
"""
)

assert_style(
"""
with x = y, a = b do
z
else
_ -> whatever
end
""",
"""
x = y
a = b
z
"""
)
end

test "doesn't false positive with vars" do
Expand Down Expand Up @@ -413,7 +428,7 @@ defmodule Styler.Style.BlocksTest do
"""
)

for nontrivial_head <- ["foo", ":ok = foo", ":ok <- foo, :ok <- bar"] do
for nontrivial_head <- ["foo", ":ok <- foo, :ok <- bar"] do
assert_style("""
with #{nontrivial_head} do
:success
Expand All @@ -423,13 +438,7 @@ defmodule Styler.Style.BlocksTest do
""")
end

assert_style(
"""
with :ok <- foo(),
do: :ok
""",
"foo()"
)
assert_style("with :ok <- foo(), do: :ok", "foo()")
end

test "rewrites non-pattern-matching lhs" do
Expand Down

0 comments on commit 0df8bc8

Please sign in to comment.