fceruti

fceruti

How to programatically format code using plugins

I’m building a library that’s constantly re generating certain modules, building them from string templates. The generated modules include certain sigils that are nicely formatted using a custom plugin.

I need to format the string before it touches disk, because there are also file watchers, who would receive the event twice if I format as a second separate step. That’s why I can’t just call System.cmd("mix format") after creating the file.

Is there something equivalent to using Code.format_string!/2 but with the ability of passing a plugin list?

Thanks!

Marked As Solved

Marcus

Marcus

If I understand right you want to format in dev mode and therefore you can access Mix. In this case you can use this:

> iex -S mix
iex(1)> {formatter, _opts} = Mix.Tasks.Format.formatter_for_file("source.ex")
{#Function<19.89531025/1 in Mix.Tasks.Format.find_formatter_for_file/2>,
 [
   sigils: [],
   plugins: [FreedomFormatter],
   trailing_comma: true,
   inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"],
   locals_without_parens: [noop: 1]
 ]}
iex(2)> formatter.("""
...(2)> defmodule    Foo do
...(2)> def foo do
...(2)> noop 5
...(2)> [
...(2)> 1,
...(2)> 2,
...(2)> ]
...(2)> end
...(2)> end
...(2)> """) |> IO.puts()
defmodule Foo do
  def foo do
    noop 5

    [
      1,
      2,
    ]
  end
end

:ok

The "source.ex" given to formatter_for_file does not have to be an existing file.

Also Liked

krasenyp

krasenyp

You can go even simpler:

def write_and_format_module(file_path, content) do
    command = """
    mix format - <<STDIN > #{file_path}
    #{content}
    STDIN
    """
    {"", 0} = System.shell(command)
    Logger.info("Re generated: #{file_path}")
  end
fceruti

fceruti

Thanks! this was it :slight_smile:

  def write_and_format_module(file_path, content) do
    :ok = file_path |> Path.dirname() |> File.mkdir_p()
    {formatter, _} = Mix.Tasks.Format.formatter_for_file("source.ex")
    File.write(file_path, formatter.(content))
    IO.puts(IO.ANSI.green() <> "* creating " <> IO.ANSI.reset() <> file_path)
  end

fceruti

fceruti

awesome, thanks!

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
hariharasudhan94
Lets say i have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; "XXX...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement