Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mix install tasks codegen #187

Merged
merged 9 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -1,6 +1 @@
[
import_deps: [:phoenix],
inputs: ["*.{ex,exs}", "{config,lib,test}/**/*.{ex,exs}"],
plugins: [Phoenix.LiveView.HTMLFormatter],
line_length: 999
]
[]
4 changes: 3 additions & 1 deletion lib/mix/live_view_native.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ defmodule Mix.LiveViewNative do
Enum.reduce(spec[:modules], %{}, fn(module, plugins) ->
if Code.ensure_loaded?(module) && Kernel.function_exported?(module, :__lvn_client__, 0) do
client = struct(module)
Map.put(plugins, client.format, client)
format = Atom.to_string(client.format)

Map.put(plugins, format, client)
else
plugins
end
Expand Down
115 changes: 115 additions & 0 deletions lib/mix/live_view_native/codegen.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
defmodule Mix.LiveViewNative.CodeGen do
@moduledoc false

alias Sourceror.Zipper

def patch(source, change, opts \\ []) do
patches = build_patches(source, change, opts)

Sourceror.patch_string(source, patches)
end

defp build_patches(source, change, opts) do
case {Keyword.get(opts, :merge), Keyword.get(opts, :inject)} do
{merge, _} when is_function(merge) ->
case merge.(source, change) do
:error -> build_patches(source, change, Keyword.delete(opts, :merge))
patches -> patches
end
{_, {:before, matcher}} -> inject_before(source, change, matcher, Keyword.get(opts, :path))
{_, {:after, matcher}} -> inject_after(source, change, matcher, Keyword.get(opts, :path))
{_, :head} -> inject_head(source, change)
{_, :eof} -> inject_eof(source, change)
_ ->
if fail_msg = Keyword.get(opts, :fail_msg) do
Mix.shell.info(fail_msg)
end

[]
end
end

defp inject_before(source, change, matcher, path) do
quoted_source = Sourceror.parse_string!(source)
case get_matched_range(quoted_source, matcher) do
{:ok, %{start: [line: line, column: column], end: _}} ->
range = %{
start: [line: line, column: column],
end: [line: line, column: column]
}

[build_patch(range, change)]
:error ->
"""
The following change failed to be applied to #{path}

#{change}
"""
|> Mix.shell.info()

[]
end
end

defp inject_after(source, change, matcher, path) do
quoted_source = Sourceror.parse_string!(source)
case get_matched_range(quoted_source, matcher) do
{:ok, %{start: [line: _, column: column], end: [line: line, column: _]}} ->
range = %{
start: [line: line + 1, column: column],
end: [line: line + 1, column: column]
}

[build_patch(range, change)]
:error ->
"""
The following change failed to be applied to #{path}

#{change}
"""
|> Mix.shell.info()

[]
end
end

defp inject_head(source, change) do
quoted_source = Sourceror.parse_string!(source)
%{start: [line: line, column: column], end: _} = Sourceror.get_range(quoted_source)

range = %{
start: [line: line, column: column],
end: [line: line, column: column]
}

[build_patch(range, change)]
end

defp inject_eof(source, change) do
quoted_source = Sourceror.parse_string!(source)
%{start: _, end: [line: line, column: column]} = Sourceror.get_range(quoted_source)

range = %{
start: [line: line + 1, column: column],
end: [line: line + 1, column: column]
}

[build_patch(range, change)]
end

defp get_matched_range(quoted, matcher) do
quoted
|> Zipper.zip()
|> Zipper.find(matcher)
|> case do
nil -> :error
found -> {:ok, Zipper.node(found) |> Sourceror.get_range()}
end
end

def build_patch(range, change),
do: %{
range: range,
change: change
}
end
5 changes: 2 additions & 3 deletions lib/mix/live_view_native/context.ex
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,8 @@ defmodule Mix.LiveViewNative.Context do
Keyword.put(opts, :context_app, String.to_atom(string))
end

defmacro compile_string(string) do
EEx.compile_string(string)
end
defmacro compile_string(string),
do: EEx.compile_string(string)

def last?(plugins, plugin),
do: Enum.at(plugins, -1) == plugin
Expand Down
2 changes: 1 addition & 1 deletion lib/mix/lvn.test_helper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ defmodule Mix.Lvn.TestHelper do

File.write!(".formatter.exs", """
[
import_deps: [:phoenix, :ecto, :ecto_sql],
import_deps: [:phoenix],
inputs: ["*.exs"]
]
""")
Expand Down
2 changes: 1 addition & 1 deletion lib/mix/tasks/lvn.ex
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ defmodule Mix.Tasks.Lvn do
defp general() do
Application.ensure_all_started(:live_view_native)
Mix.shell().info "LiveView Native v#{Application.spec(:live_view_native, :vsn)}"
Mix.shell().info "Deploy LiveView applications to anything with a screen."
Mix.shell().info "Build LiveView applications for anything with a screen."
Mix.shell().info "\n## Options\n"
Mix.shell().info "-v, --version # Prints LiveView Native version\n"
Mix.Tasks.Help.run(["--search", "lvn."])
Expand Down
167 changes: 9 additions & 158 deletions lib/mix/tasks/lvn.gen.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ defmodule Mix.Tasks.Lvn.Gen do
use Mix.Task

alias Mix.LiveViewNative.Context

import Mix.LiveViewNative.Context, only: [
compile_string: 1,
last?: 2
]

@shortdoc "Generates the Native module and prints configuration instructions"
@shortdoc "Generates the Native module"

@moduledoc """
#{@shortdoc}
Expand All @@ -19,8 +19,6 @@ defmodule Mix.Tasks.Lvn.Gen do

## Options

* `--no-copy` - don't copy the `Native` module into your application
* `--no-info` - don't print configuration info
* `--no-live-form` - don't include `LiveViewNative.LiveForm` content in the `Native` module
"""

Expand All @@ -33,168 +31,21 @@ defmodule Mix.Tasks.Lvn.Gen do
)
end

context = Context.build(args, __MODULE__)

if Keyword.get(context.opts, :copy, true) do
files = files_to_be_generated(context)
Context.prompt_for_conflicts(files)

copy_new_files(context, files)
end

if Keyword.get(context.opts, :info, true) do
print_shell_instructions(context)
end
end

defp print_shell_instructions(context) do
context
|> print_instructions()
|> print_config()
|> print_dev()
|> print_router()
|> print_endpoint()
end

defp print_instructions(context) do
"""
The following are configurations that should be added to your application.

Follow each section as there are multiple files that require editing.
"""
|> Mix.shell().info()

context
args
|> Context.build(__MODULE__)
|> gen()
end

defp print_config(context) do
plugins = Mix.LiveViewNative.plugins() |> Map.values()

plugins? = length(plugins) > 0

"""
\e[93;1m# config/config.exs\e[0m

# \e[91;1mLVN - Required\e[0m
# Registers each available plugin<%= unless plugins? do %>
\e[93;1m# Hint: if you add this config to your app populated with client plugins
# and run `mix lvn.gen` this configuration's placeholders will be populated\e[0m<% end %>
config :live_view_native, plugins: [\e[32;1m<%= if plugins? do %><%= for plugin <- plugins do %>
LiveViewNative.<%= plugin.module_suffix %><%= unless last?(plugins, plugin) do %>,<% end %><% end %><% else %>
# LiveViewNative.SwiftUI<% end %>\e[0m
]

# \e[91;1mLVN - Required\e[0m
# Each format must be registered as a mime type add to
# existing configuration if one exists as this will overwrite
config :mime, :types, %{\e[32;1m<%= if plugins? do %><%= for plugin <- plugins do %>
"text/<%= plugin.format %>" => ["<%= plugin.format %>"]<%= unless last?(plugins, plugin) do %>,<% end %><% end %><% else %>
# "text/swiftui" => ["swiftui"]<% end %>\e[0m
}

# \e[91;1mLVN - Required\e[0m
# Phoenix must know how to encode each LVN format
config :phoenix_template, :format_encoders, [\e[32;1m<%= if plugins? do %><%= for plugin <- plugins do %>
<%= plugin.format %>: Phoenix.HTML.Engine<%= unless last?(plugins, plugin) do %>,<% end %><% end %><% else %>
# swiftui: Phoenix.HTML.Engine<% end %>\e[0m
]

# \e[91;1mLVN - Required\e[0m
# Phoenix must know how to compile neex templates
config :phoenix, :template_engines, [
\e[32;1mneex: LiveViewNative.Engine\e[0m
]
"""
|> compile_string()
|> Mix.shell().info()

context
end

defp print_dev(context) do
"""
\e[93;1m# config/dev.exs\e[0m

# \e[36mLVN - Optional\e[0m
# Allows LVN templates to be subject to LiveReload changes
config :<%= context.context_app %>, <%= inspect context.web_module %>.Endpoint,
live_reload: [
patterns: [
~r"priv/static/(?!uploads/).*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/anotherone_web/(controllers|live|components)/.*(ex|heex\e[32;1m|neex\e[0m)$"
]
]
"""
|> compile_string()
|> Mix.shell().info()

context
end

defp print_router(context) do
plugins = Mix.LiveViewNative.plugins() |> Map.values()

plugins? = length(plugins) > 0

layouts =
[html: {Module.concat(context.web_module, Layouts), :root}]
|> Kernel.++(
plugins
|> Enum.map(&({&1.format, {Module.concat([context.web_module, Layouts, &1.module_suffix]), :root}})
))

"""
\e[93;1m# lib/<%= Macro.underscore(context.web_module) %>/router.ex\e[0m

# \e[91;1mLVN - Required\e[0m
# add the formats to the `accepts` plug for the pipeline used by your LiveView Native app
plug :accepts, [
"html",\e[32;1m<%= if plugins? do %><%= for plugin <- plugins do %>
"<%= plugin.format %>"<%= unless last?(plugins, plugin) do %>,<% end %><% end %><% else %>
# "swiftui"<% end %>\e[0m
]

# \e[91;1mLVN - Required\e[0m
# add the root layout for each format
plug :put_root_layout, [
html: <%= inspect(layouts[:html]) %>,\e[32;1m<%= if plugins? do %><%= for plugin <- plugins do %>
<%= plugin.format %>: <%= inspect(layouts[plugin.format]) %><%= unless last?(plugins, plugin) do %>,<% end %><% end %><% else %>
# swiftui: {<%= inspect(layouts[:html] |> elem(0)) %>, :root}<% end %>\e[0m
]
"""
|> compile_string()
|> Mix.shell().info()

context
end

defp print_endpoint(context) do
"""
\e[93;1m# lib/<%= Macro.underscore(context.web_module) %>/endpoint.ex\e[0m

# \e[36mLVN - Optional\e[0m
# Add the LiveViewNative.LiveReloader to your endpoint
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
\e[32;1mplug LiveViewNative.LiveReloader\e[0m
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :form_demo
end
"""
|> compile_string()
|> Mix.shell.info()

context
def gen(context) do
files = files_to_be_generated(context)
Context.prompt_for_conflicts(files)
copy_new_files(context, files)
end

@doc false
def switches, do: [
context_app: :string,
web: :string,
info: :boolean,
copy: :boolean,
live_form: :boolean
]

Expand Down
Loading
Loading