Skip to content

Commit

Permalink
sort directive: sort values of keys. Closes #208
Browse files Browse the repository at this point in the history
  • Loading branch information
novaugust committed Jan 13, 2025
1 parent 5d3d620 commit d132d79
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 3 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
they can and will change without that change being reflected in Styler's semantic version.
## main

### Improvements

- `# styler:sort` can be used to sort values of key-value pairs. eg, sort the value of a single key in a map (Closes #208, h/t @ypconstante)

## 1.3.1

### Improvements
Expand Down
1 change: 1 addition & 0 deletions lib/style.ex
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ defmodule Styler.Style do
def meta({_, meta, _}), do: meta
# kwl tuple ala a: :b
def meta({{_, meta, _}, _}), do: meta
def meta(_), do: nil

@doc """
Returns all comments "for" a node, including on the line before it.
Expand Down
11 changes: 8 additions & 3 deletions lib/style/comment_directives.ex
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ defmodule Styler.Style.CommentDirectives do
|> Enum.map(& &1.line)
|> Enum.reduce({zipper, ctx.comments}, fn line, {zipper, comments} ->
found =
Zipper.find(zipper, fn
{_, meta, _} -> Keyword.get(meta, :line, -1) >= line
_ -> false
Zipper.find(zipper, fn node ->
node_line = Style.meta(node)[:line] || -1
node_line >= line
end)

if found do
Expand Down Expand Up @@ -102,5 +102,10 @@ defmodule Styler.Style.CommentDirectives do
{{:@, m, [{a, am, [assignment]}]}, comments}
end

defp sort({key, value}, comments) do
{value, comments} = sort(value, comments)
{{key, value}, comments}
end

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

test "inside keywords" do
assert_style(
"""
%{
key:
# styler:sort
[
3,
2,
1
]
}
""",
"""
%{
# styler:sort
key: [
1,
2,
3
]
}
"""
)

assert_style(
"""
%{
# styler:sort
key: [
3,
2,
1
]
}
""",
"""
%{
# styler:sort
key: [
1,
2,
3
]
}
"""
)
end

test "sorts sigils" do
assert_style("# styler:sort\n~w|c a b|", "# styler:sort\n~w|a b c|")

Expand Down

0 comments on commit d132d79

Please sign in to comment.