From c95b0ba8b0b56738aaeed81e990b7e3448845a1c Mon Sep 17 00:00:00 2001 From: Matt Enlow Date: Mon, 15 Jul 2024 16:20:28 -0600 Subject: [PATCH] Rewrite `with true <- ...` to if statements. Closes #173 --- CHANGELOG.md | 8 +++++++- lib/style/blocks.ex | 16 ++++++++++++++++ test/style/blocks_test.exs | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 552943b..d31e73c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/lib/style/blocks.ex b/lib/style/blocks.ex index f18ace1..a6f5cff 100644 --- a/lib/style/blocks.ex +++ b/lib/style/blocks.ex @@ -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 ¯\_(ツ)_/¯ diff --git a/test/style/blocks_test.exs b/test/style/blocks_test.exs index 52a9f93..79d8ddc 100644 --- a/test/style/blocks_test.exs +++ b/test/style/blocks_test.exs @@ -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( """