-
Notifications
You must be signed in to change notification settings - Fork 0
/
prettier_formatter.ex
82 lines (58 loc) · 1.78 KB
/
prettier_formatter.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
defmodule PrettierFormatter do
@moduledoc """
A formatter that can be plugged in to `mix format` in order to format javascript
and css files.
## Usage
Add `PrettierFormatter` to the `.formatter.exs` plugin list.
```
[
plugins: [PrettierFormatter],
inputs: [
...
"assets/js/**/*.{js,ts,jsx,tsx}",
"assets/tailwind.config.js",
"assets/css/**/*.css"
]
]
```
"""
alias PrettierFormatter.Installer
require Logger
@behaviour Mix.Tasks.Format
@latest_version "3.3.3"
def configured_version do
unless Application.get_env(:prettier_formatter, :version) do
Logger.warning("""
Prettier version is not configured. Please set it in your config files:
config :prettier_formatter, :version, "#{latest_version()}"
""")
end
Application.get_env(:prettier_formatter, :version, latest_version())
end
@impl true
def features(_opts) do
[extensions: ~w(.js .ts .jsx .tsx .css)]
end
@impl true
def format(contents, opts) do
version = configured_version()
unless Installer.installed?(version) == :ok do
raise """
Prettier #{version} is not installed.
To install it, run
mix prettier.install
"""
end
extension = Keyword.fetch!(opts, :extension)
do_format(contents, extension)
end
defp do_format(contents, extension) when extension in ~w(.js .ts .jsx .tsx),
do: run_format(contents, "typescript")
defp do_format(contents, extension) when extension in ~w(.css), do: run_format(contents, "css")
defp run_format(contents, parser) do
contents = String.replace(contents, "'", "'\"'\"'")
{contents, 0} = System.shell("echo '#{contents}' | prettier --parser #{parser}")
contents
end
defp latest_version, do: @latest_version
end