From e148dda41e1ac8408dede3bc2431fa4997ade7a9 Mon Sep 17 00:00:00 2001 From: Zach Daniel Date: Fri, 6 Sep 2024 15:14:59 -0400 Subject: [PATCH] improvement: add `add_bypass` and `add_policy` igniter utilities --- lib/ash/resource/igniter.ex | 58 +++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/lib/ash/resource/igniter.ex b/lib/ash/resource/igniter.ex index 625c3ae1..fc56650f 100644 --- a/lib/ash/resource/igniter.ex +++ b/lib/ash/resource/igniter.ex @@ -47,6 +47,64 @@ defmodule Ash.Resource.Igniter do [Ash.Resource | List.wrap(Application.get_env(app_name, :base_resources))] end + @doc "Adds a bypass to the top of the resource's `policies` block" + def add_bypass(igniter, resource, condition, body) do + bypass = + quote do + policies do + bypass unquote(condition) do + unquote(body) + end + end + end + |> Sourceror.to_string() + |> Sourceror.parse_string!() + + Igniter.Code.Module.find_and_update_module!(igniter, resource, fn zipper -> + with {:ok, zipper} <- + Igniter.Code.Function.move_to_function_call_in_current_scope( + zipper, + :policies, + 1 + ), + {:ok, zipper} <- Igniter.Code.Common.move_to_do_block(zipper) do + {:ok, Igniter.Code.Common.add_code(zipper, bypass, :before)} + else + _ -> + {:ok, Igniter.Code.Common.add_code(zipper, bypass)} + end + end) + end + + @doc "Adds a policy to the bottom of the resource's `policies` block" + def add_policy(igniter, resource, condition, body) do + policy = + quote do + policies do + policy unquote(condition) do + unquote(body) + end + end + end + |> Sourceror.to_string() + |> Sourceror.parse_string!() + + Igniter.Code.Module.find_and_update_module!(igniter, resource, fn zipper -> + with {:ok, zipper} <- + Igniter.Code.Function.move_to_function_call_in_current_scope( + zipper, + :policies, + 1 + ), + {:ok, zipper} <- Igniter.Code.Common.move_to_do_block(zipper) do + {:ok, Igniter.Code.Common.add_code(zipper, policy, :after)} + else + _ -> + {:ok, Igniter.Code.Common.add_code(zipper, policy)} + end + end) + end + @doc "Adds the given code block to the resource's `attributes` block" def add_attribute(igniter, resource, attribute) do Igniter.Code.Module.find_and_update_module!(igniter, resource, fn zipper ->