Hash :
b33044f6
Author :
Thomas de Grivel
Date :
2022-04-10T20:42:13
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
defmodule Pygmentize do
require Logger
def random_string() do
:crypto.strong_rand_bytes(16)
|> Base.url_encode64()
end
def lexer(filename) do
cmd = "pygmentize"
args = ["-N", filename |> String.replace(~r/ /, "_")]
Logger.info(inspect([cmd | args]))
{out, status} = System.cmd(cmd, args)
case status do
0 -> out |> String.trim()
_ -> ""
end
end
def html(content, filename) do
lexer = lexer(filename)
cmd = "./bin/size #{byte_size(content)} pygmentize -l #{lexer} -f html"
Logger.info("EXEC #{cmd}")
port = Port.open({:spawn, cmd}, [:binary, :use_stdio, :exit_status, :stderr_to_stdout])
Port.monitor(port)
send(port, {self(), {:command, content}})
html_port(content, port, [])
end
def html_port(content, port, acc) do
receive do
{^port, {:exit_status, 0}} ->
acc |> Enum.reverse() |> Enum.join()
{^port, {:exit_status, _status}} ->
#IO.inspect("pygmentize exited with status #{status}")
nil
{^port, {:data, data}} ->
html_port(content, port, [data | acc])
{:DOWN, _, :port, ^port, _reason} ->
#IO.inspect({:down, reason})
acc |> Enum.reverse() |> Enum.join()
_x ->
#IO.inspect(x)
html_port(content, port, acc)
after 1000 ->
result = acc |> Enum.reverse() |> Enum.join()
if result == "" do
nil
else
result
end
end
end
end