Skip to content

Commit e13c944

Browse files
JakeBeckerJosé Valim
authored andcommitted
Add Mix.Tasks.Format.formatter_opts_for_file/2 (#7457)
Returns options to be used for a given file - useful for editor integrations formatting unsaved files. Signed-off-by: José Valim <[email protected]>
1 parent 6a0e939 commit e13c944

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

lib/mix/lib/mix/tasks/format.ex

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,19 @@ defmodule Mix.Tasks.Format do
142142
|> check!()
143143
end
144144

145+
@doc """
146+
Returns formatter options to be used for the given file.
147+
"""
148+
def formatter_opts_for_file(file, opts \\ []) do
149+
{dot_formatter, formatter_opts} = eval_dot_formatter(opts)
150+
151+
{formatter_opts_and_subs, _sources} =
152+
eval_deps_and_subdirectories(dot_formatter, [], formatter_opts, [dot_formatter])
153+
154+
split = file |> Path.relative_to_cwd() |> Path.split()
155+
find_formatter_opts_for_file(split, formatter_opts_and_subs)
156+
end
157+
145158
defp eval_dot_formatter(opts) do
146159
cond do
147160
dot_formatter = opts[:dot_formatter] ->

lib/mix/test/mix/tasks/format_test.exs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,9 @@ defmodule Mix.Tasks.FormatTest do
213213
[inputs: "a.ex", locals_without_parens: [my_fun: 2]]
214214
""")
215215

216+
formatter_opts = Mix.Tasks.Format.formatter_opts_for_file("lib/extra/a.ex")
217+
assert [my_fun: 2] = Keyword.get(formatter_opts, :locals_without_parens)
218+
216219
File.write!("lib/a.ex", """
217220
my_fun :foo, :bar
218221
other_fun :baz
@@ -280,6 +283,9 @@ defmodule Mix.Tasks.FormatTest do
280283
# Let's check that the manifest gets updated if it's stale.
281284
File.touch!(manifest_path, {{1970, 1, 1}, {0, 0, 0}})
282285

286+
formatter_opts = Mix.Tasks.Format.formatter_opts_for_file("a.ex")
287+
assert [my_fun: 2] = Keyword.get(formatter_opts, :locals_without_parens)
288+
283289
Mix.Tasks.Format.run(["a.ex"])
284290
assert File.stat!(manifest_path).mtime > {{1970, 1, 1}, {0, 0, 0}}
285291
end)
@@ -357,6 +363,9 @@ defmodule Mix.Tasks.FormatTest do
357363
File.touch!("lib/extra/.formatter.exs", {{2030, 1, 1}, {0, 0, 0}})
358364
Mix.Tasks.Format.run([])
359365

366+
formatter_opts = Mix.Tasks.Format.formatter_opts_for_file("lib/extra/a.ex")
367+
assert [other_fun: 1] = Keyword.get(formatter_opts, :locals_without_parens)
368+
360369
assert File.read!("lib/extra/a.ex") == """
361370
my_fun(:foo, :bar)
362371
other_fun :baz

0 commit comments

Comments
 (0)