From 3c13f41312f1046de7790f3358fd9fdc32ed25df Mon Sep 17 00:00:00 2001 From: Matt Enlow Date: Thu, 25 Jan 2024 10:50:14 -0700 Subject: [PATCH] if not x, do: y => unless x, do: y --- lib/style/blocks.ex | 4 ++++ test/style/blocks_test.exs | 12 +++++------- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/style/blocks.ex b/lib/style/blocks.ex index 185e4954..474d45c4 100644 --- a/lib/style/blocks.ex +++ b/lib/style/blocks.ex @@ -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} diff --git a/test/style/blocks_test.exs b/test/style/blocks_test.exs index 25d5829f..5ee358f8 100644 --- a/test/style/blocks_test.exs +++ b/test/style/blocks_test.exs @@ -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( @@ -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