Skip to content

Instantly share code, notes, and snippets.

@NduatiK
Last active June 4, 2024 13:52
Show Gist options
  • Save NduatiK/4a6c78ed893fca55a5186270ca204c43 to your computer and use it in GitHub Desktop.
Save NduatiK/4a6c78ed893fca55a5186270ca204c43 to your computer and use it in GitHub Desktop.
A diff-based solution to the problem of undoing the effects of formatting in the Igniter tool by the Ash team. Doesn't work for all the edge cases.

Igniter Diff

Mix.install([
  {:differ, "~> 0.1.1"}
])

UnFormat

defmodule UnFormat do
  def run(input, output) do
    input
    |> Differ.diff(output)
    |> Enum.flat_map(fn
      {op, str} ->
        cond do
          # Undo whitespace changes
          op == :del && str =~ ~r"^\s*$" ->
            [{:eq, str}]

          op == :ins && str =~ ~r"^\s*$" ->
            []

          # Undo opening parens changes
          op == :del && str =~ ~r"^[\s\(]*$" ->
            [{:eq, str}]

          op == :ins && str =~ ~r"^[\s\(]*$" ->
            []

          # Undo closing parens changes
          op == :del && str =~ ~r"^[\s\)]*$" ->
            [{:eq, str}]

          op == :ins && str =~ ~r"^[\s\)]*$" ->
            []

          true ->
            [{op, str}]
        end
    end)
    |> then(&Differ.patch!(input, &1))
  end
end
{:module, UnFormat, <<70, 79, 82, 49, 0, 0, 12, ...>>, {:run, 2}}

Whitespace Deleted

input =
  """
  config :fake,
            
            :buz,        (([:blat]))
    config :fake2, 1 + 1
  """

output =
  """
  config :fake, :buz, [:blat]
  config :fake2, (1 + 1)
  config :fake, foo: "baz"
  """

IO.puts(UnFormat.run(input, output))
config :fake,
          
          :buz,        (([:blat]))
  config :fake2, 1 + 1
config :fake, foo: "baz"

:ok

Whitespace Inserted

input =
  """
  config :fake, :buz, [1,2,3]
  """

output =
  """
  config :fake, :buz, [
    1,
    2,
    3]
  config :fake, foo: "baz"
  """

IO.puts(UnFormat.run(input, output))
config :fake, :buz, [1,2,3]
config :fake, foo: "baz"

:ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment