Hi everyone
I’m trying to create a CLI with Elixir to read and follow a stdin. It reads the file, but don’t process the inserted lines after the app start. I tried with escript and release. I want to run something like this
cli_command < file
For releases I created a GenServer that start start call a loop module on start
defmodule CLI.Server do
@moduledoc """
CLI Server
"""
use GenServer
def start_link(state) do
GenServer.start_link(__MODULE__, state, name: __MODULE__)
end
def init(opts \\ []) do
send(self(), :listen)
opts = [
input: Keyword.get(opts, :input, :stdio),
writer: Keyword.get(opts, :writer, fn content -> IO.write(:stdio, content) end)
]
{:ok, opts}
end
def handle_info(:listen, [input: input, writer: writer] = state) do
CLI.Handler.listen(input, writer)
{:noreply, state}
end
end
defmodule CLI.Handler do
def listen(input, writer) do
input
|> IO.stream(:line)
|> Enum.each(fn line ->
response = CLI.Operation.run(line)
writer.(response)
writer.("\n")
end)
listen(input, writer)
end
end
For escript I used something like CLI.Handler
as main_module
.
For both cases it didn’t write the file following lines. Any idea what is the best practice to do this?