-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Run a NervesHub script on device (#207)
* Run a NervesHub script on device Evaluate a script locally on device from NervesHub instead of relying on the console channel. Bumps the api version so NervesHub is aware this is possible on the connecting device. * Run script capture in a separate process In case of bad code we won't crash the socket process or potentially leave the socket process with a bad group leader
- Loading branch information
Showing
3 changed files
with
65 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
defmodule NervesHubLink.Script do | ||
use GenServer | ||
|
||
@doc """ | ||
Run a script from NervesHub and capture its output | ||
""" | ||
def capture(text, ref) do | ||
_ = GenServer.start_link(__MODULE__, {self(), text, ref}) | ||
|
||
:ok | ||
end | ||
|
||
@impl GenServer | ||
def init({pid, text, ref}) do | ||
state = %{pid: pid, text: text, ref: ref} | ||
{:ok, state, {:continue, :capture}} | ||
end | ||
|
||
@impl GenServer | ||
def handle_continue(:capture, state) do | ||
# Inspired from ExUnit.CaptureIO | ||
# https://github.com/elixir-lang/elixir/blob/main/lib/ex_unit/lib/ex_unit/capture_io.ex | ||
{:ok, string_io} = StringIO.open("") | ||
|
||
Process.group_leader(self(), string_io) | ||
|
||
{result, output} = | ||
try do | ||
Code.eval_string(state.text) | ||
catch | ||
kind, reason -> | ||
{:ok, {_input, output}} = StringIO.close(string_io) | ||
result = Exception.format_banner(kind, reason, __STACKTRACE__) | ||
output = output <> "\n" <> result | ||
{nil, output} | ||
else | ||
{result, _binding} -> | ||
{:ok, {_input, output}} = StringIO.close(string_io) | ||
{result, output} | ||
end | ||
|
||
send(state.pid, {"scripts/run", state.ref, output, result}) | ||
|
||
{:stop, :normal, state} | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters