Skip to content

Commit

Permalink
Rewrite with true <- ... to if statements. Closes #173
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust committed Jul 15, 2024
1 parent 0df8bc8 commit c95b0ba
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,15 @@ they can and will change without that change being reflected in Styler's semanti

## main

### Improvements

#### `with`

* remove `with` structure with no left arrows in its head to be normal code (#174)
* `with true <- x(), do: y` => `if x(), do: y` (#173)

### 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
16 changes: 16 additions & 0 deletions lib/style/blocks.ex
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,22 @@ defmodule Styler.Style.Blocks do
run({{:case, m, [single_statement, clauses]}, zm}, ctx)
end

# `with true <- x, do: bar` =>`if x, do: bar`
def run({{:with, m, [{:<-, _, [{_, _, [true]}, rhs]}, [do_kwl]]}, _} = zipper, ctx) do
children =
case rhs do
# `true <- foo || {:error, :shouldve_used_an_if_statement}``
# turn the rhs of an `||` into an else body
{:||, _, [head, else_body]} ->
[head, [do_kwl, {{:__block__, [line: m[:line] + 2], [:else]}, Style.shift_line(else_body, 3)}]]

_ ->
[rhs, [do_kwl]]
end

{:cont, Zipper.replace(zipper, {:if, m, children}), ctx}
end

# 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 ¯\_(ツ)_/¯
Expand Down
34 changes: 34 additions & 0 deletions test/style/blocks_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,40 @@ defmodule Styler.Style.BlocksTest do
)
end

test "with to if" do
assert_style(
"""
with true <- foo do
boop
bar
end
""",
"""
if foo do
boop
bar
end
"""
)

assert_style "with true <- x, do: bar", "if x, do: bar"

assert_style(
"""
with true <- foo || {:error, :shouldve_used_an_if_statement} do
bar
end
""",
"""
if foo do
bar
else
{:error, :shouldve_used_an_if_statement}
end
"""
)
end

test "switches keyword do to block do when adding postroll" do
assert_style(
"""
Expand Down

0 comments on commit c95b0ba

Please sign in to comment.