Skip to content

Commit

Permalink
improvement: allow modifications of supertree in Zipper.within/2 (#…
Browse files Browse the repository at this point in the history
…157)

* improvement: allow modifications of `supertree` in `Zipper.within/2`

* test: add a test for `within/2` plus supertree
  • Loading branch information
zachdaniel authored Jul 22, 2024
1 parent 8437264 commit 04ffeeb
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/sourceror/zipper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,6 @@ defmodule Sourceror.Zipper do
"""
def within(%Z{} = zipper, fun) when is_function(fun, 1) do
updated = zipper |> subtree() |> fun.() |> top()
into(updated, zipper)
into(updated, updated.supertree || zipper)
end
end
40 changes: 40 additions & 0 deletions test/zipper_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,46 @@ defmodule SourcerorTest.ZipperTest do
config :unrelated, key: :dont_change_me\
"""
end

test "uses any modified supertree" 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))
# This is simulating a "modify and append code" operation (rare, but good for testing this case)
|> Z.within(fn zipper ->
zipper
|> Map.update!(:supertree, fn supertree ->
upwards = Z.up(supertree)
{:__block__, _, code} = upwards.node

upwards
|> Z.replace(
{:__block__, [],
List.insert_at(code, Enum.count(supertree.path.left || []) + 1, :new_code)}
)
|> Z.find(&(&1 == zipper.node))
end)
|> 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
:new_code
config :unrelated, key: :dont_change_me\
"""
end
end

describe "search_pattern/2 with cursor" do
Expand Down

0 comments on commit 04ffeeb

Please sign in to comment.