Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Sourceror.Zipper.within/2 #142

Merged
merged 1 commit into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/sourceror/zipper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -474,4 +474,15 @@ defmodule Sourceror.Zipper do
@spec subtree(t) :: t
@compile {:inline, subtree: 1}
def subtree(%Z{} = zipper), do: %{zipper | path: nil}

@doc """
Runs the function `fun` on the subtree of the currently focused `node` and
returns the updated `zipper`.

`fun` must return a zipper, which may be positioned at the top of the subtree.
"""
def within(%Z{} = zipper, fun) when is_function(fun, 1) do
updated = zipper |> subtree() |> fun.() |> top()
into(updated, zipper)
end
end
32 changes: 31 additions & 1 deletion test/zipper_test.exs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
defmodule SourcerorTest.ZipperTest do
use ExUnit.Case, async: true
doctest Sourceror.Zipper, except: [:moduledoc]

doctest Sourceror.Zipper, import: true, except: [:moduledoc]

alias Sourceror.Zipper, as: Z

Expand Down Expand Up @@ -685,4 +686,33 @@ defmodule SourcerorTest.ZipperTest do
assert :ok = Z.Inspect.default_inspect_as(:as_ast)
end
end

describe "within/2" do
test "executes a function within a zipper" do
code = """
config :target, key: :change_me

config :unrelated, key: :dont_change_me
"""

updated =
code
|> Sourceror.parse_string!()
|> Z.zip()
|> Z.find(&match?({:config, _, [{:__block__, _, [:target]} | _]}, &1))
|> Z.within(fn zipper ->
zipper
|> Z.find(&match?({{:__block__, _, [:key]}, _value}, &1))
|> Z.update(fn {key, _value} -> {key, {:__block__, [], [:changed]}} end)
end)
|> Z.root()
|> Sourceror.to_string()

assert updated == """
config :target, key: :changed

config :unrelated, key: :dont_change_me\
"""
end
end
end
Loading