Skip to content

Commit

Permalink
styler:sort arbitrary ast within do end blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust committed Jan 16, 2025
1 parent 9b0207b commit efb2cb9
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
28 changes: 28 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,34 @@
they can and will change without that change being reflected in Styler's semantic version.
## main

### Improvements

- `# styler:sort` will sort arbitrary ast nodes within a `do end` block:

Given:
# styler:sort
my_macro "some arg" do
another_macro :q
another_macro :w
another_macro :e
another_macro :r
another_macro :t
another_macro :y
end

We get
# styler:sort
my_macro "some arg" do
another_macro :e
another_macro :q
another_macro :r
another_macro :t
another_macro :w
another_macro :y
end



### Fixes

- fix a bug in comment-movement when multiple `# styler:sort` directives are added to a file at the same time
Expand Down
18 changes: 18 additions & 0 deletions lib/style/comment_directives.ex
Original file line number Diff line number Diff line change
Expand Up @@ -106,5 +106,23 @@ defmodule Styler.Style.CommentDirectives do
{{key, value}, comments}
end

# sorts arbitrary ast nodes within a `do end` list
defp sort({f, m, args} = node, comments) do
if m[:do] && m[:end] && match?([{{:__block__, _, [:do]}, {:__block__, _, _}}], List.last(args)) do
{[{{:__block__, m1, [:do]}, {:__block__, m2, nodes}}], args} = List.pop_at(args, -1)

{nodes, comments} =
nodes
|> Enum.sort_by(&Macro.to_string/1)
|> Style.order_line_meta_and_comments(comments, m[:line])

args = List.insert_at(args, -1, [{{:__block__, m1, [:do]}, {:__block__, m2, nodes}}])

{{f, m, args}, comments}
else
{node, comments}
end
end

defp sort(x, comments), do: {x, comments}
end
33 changes: 33 additions & 0 deletions test/style/comment_directives_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,39 @@ defmodule Styler.Style.CommentDirectivesTest do
)
end

test "nodes within a do end block" do
assert_style(
"""
# styler:sort
my_macro "some arg" do
another_macro :q
# w
another_macro :w
another_macro :e
# r comment 1
# r comment 2
another_macro :r
another_macro :t
another_macro :y
end
""",
"""
# styler:sort
my_macro "some arg" do
another_macro(:e)
another_macro(:q)
# r comment 1
# r comment 2
another_macro(:r)
another_macro(:t)
# w
another_macro(:w)
another_macro(:y)
end
"""
)
end

test "treats comments nicely" do
assert_style(
"""
Expand Down

0 comments on commit efb2cb9

Please sign in to comment.