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

improvement: allow modifications of supertree in Zipper.within/2 #157

Merged
merged 2 commits into from
Jul 22, 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
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
Loading