Skip to content

Commit

Permalink
Correctly shift all meta line values when shrinking function heads. C…
Browse files Browse the repository at this point in the history
…loses #67
  • Loading branch information
novaugust committed Nov 7, 2023
1 parent c9fba31 commit 45afdaa
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 11 deletions.
13 changes: 13 additions & 0 deletions lib/style.ex
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ defmodule Styler.Style do
end)
end

def shift_line(ast_node, delta) do
shift_line = &Keyword.replace_lazy(&1, :line, fn line -> line + delta end)

update_all_meta(ast_node, fn meta ->
meta
|> shift_line.()
|> Keyword.replace_lazy(:closing, shift_line)
|> Keyword.replace_lazy(:end_of_expression, shift_line)
|> Keyword.replace_lazy(:last, shift_line)
|> Keyword.replace_lazy(:end, shift_line)
end)
end

@doc "Traverses an ast node, updating all nodes' meta with `meta_fun`"
def update_all_meta(node, meta_fun) do
node
Expand Down
13 changes: 2 additions & 11 deletions lib/style/defs.ex
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,14 @@ defmodule Styler.Style.Defs do
else
do_line = do_meta[:line]
delta = def_line - do_line
move_up = &(&1 + delta)

def_meta =
def_meta
|> put_in([:do, :line], def_line)
|> update_in([:end, :line], move_up)
|> update_in([:end, :line], &(&1 + delta))

head = Style.set_line(head, def_line)
body = Style.update_all_meta(body, shift_lines(move_up))
body = Style.shift_line(body, delta)
node = {def, def_meta, [head, body]}

comments =
Expand All @@ -110,12 +109,4 @@ defmodule Styler.Style.Defs do
end

def run(zipper, ctx), do: {:cont, zipper, ctx}

defp shift_lines(line_mover) do
fn meta ->
meta
|> Keyword.replace_lazy(:line, line_mover)
|> Keyword.replace_lazy(:closing, &Keyword.replace_lazy(&1, :line, line_mover))
end
end
end
18 changes: 18 additions & 0 deletions test/style/defs_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,24 @@ defmodule Styler.Style.DefsTest do
use Styler.StyleCase, async: true

describe "run" do
test "comments stay put when we can't shrink the head, even with blocks" do
assert_style("""
def my_function(
so_long_that_this_head_will_not_fit_on_one_lineso_long_that_this_head_will_not_fit_on_one_line,
so_long_that_this_head_will_not_fit_on_one_line
) do
result =
case foo do
:bar -> :baz
:baz -> :bong
end
# My comment
Context.process(result)
end
""")
end

test "function with do keyword" do
assert_style(
"""
Expand Down

0 comments on commit 45afdaa

Please sign in to comment.