igniter/lib/formatter.ex

96 lines
2.4 KiB
Elixir
Raw Normal View History

2024-05-28 15:30:41 +12:00
defmodule Igniter.Formatter do
@moduledoc "Codemods and utilities for interacting with `.formatter.exs` files"
2024-06-13 10:22:08 +12:00
alias Igniter.Code.Common
2024-05-28 15:30:41 +12:00
alias Sourceror.Zipper
@default_formatter """
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
"""
2024-06-13 10:22:08 +12:00
@doc """
Adds a new dep to the list of imported deps in the root `.formatter.exs`
"""
@spec import_dep(Igniter.t(), dep :: atom) :: Igniter.t()
2024-05-28 15:30:41 +12:00
def import_dep(igniter, dep) do
igniter
|> Igniter.include_or_create_elixir_file(".formatter.exs", @default_formatter)
2024-06-04 05:13:49 +12:00
|> Igniter.update_elixir_file(".formatter.exs", fn zipper ->
zipper
|> Zipper.down()
|> case do
nil ->
code =
quote do
[import_deps: [unquote(dep)]]
end
2024-05-28 15:30:41 +12:00
2024-06-13 10:22:08 +12:00
Common.add_code(zipper, code)
2024-06-04 05:13:49 +12:00
zipper ->
zipper
|> Zipper.rightmost()
2024-06-13 10:22:08 +12:00
|> Igniter.Code.Keyword.put_in_keyword([:import_deps], [dep], fn nested_zipper ->
Igniter.Code.List.prepend_new_to_list(
2024-06-04 05:13:49 +12:00
nested_zipper,
dep
)
end)
|> case do
{:ok, zipper} ->
zipper
2024-05-28 15:30:41 +12:00
2024-06-04 05:13:49 +12:00
:error ->
zipper
end
end
2024-05-28 15:30:41 +12:00
end)
end
2024-06-13 10:22:08 +12:00
@doc """
Adds a new plugin to the list of plugins in the root `.formatter.exs`
"""
@spec add_formatter_plugin(Igniter.t(), plugin :: module()) :: Igniter.t()
2024-05-28 15:30:41 +12:00
def add_formatter_plugin(igniter, plugin) do
igniter
|> Igniter.include_or_create_elixir_file(".formatter.exs", @default_formatter)
2024-06-04 05:13:49 +12:00
|> Igniter.update_elixir_file(".formatter.exs", fn zipper ->
zipper
|> Zipper.down()
|> case do
nil ->
code =
quote do
[plugins: [unquote(plugin)]]
end
2024-05-28 15:30:41 +12:00
2024-06-04 05:13:49 +12:00
zipper
2024-06-13 10:22:08 +12:00
|> Common.add_code(code)
2024-06-04 05:13:49 +12:00
zipper ->
zipper
|> Zipper.rightmost()
2024-06-13 10:22:08 +12:00
|> Igniter.Code.Keyword.put_in_keyword(
[:plugins],
[Spark.Formatter],
fn nested_zipper ->
Igniter.Code.List.prepend_new_to_list(
nested_zipper,
Spark.Formatter
)
end
)
2024-06-04 05:13:49 +12:00
|> case do
{:ok, zipper} ->
zipper
2024-05-28 15:30:41 +12:00
2024-06-04 05:13:49 +12:00
_ ->
zipper
end
end
2024-05-28 15:30:41 +12:00
end)
end
end