Hash :
b5e65900
Author :
Thomas de Grivel
Date :
2022-03-18T17:53:10
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
defmodule Pygmentize do
def random_string() do
:crypto.strong_rand_bytes(16)
|> Base.url_encode64()
end
def lexer(filename) do
{out, status} = System.cmd("pygmentize", ["-N", filename |> String.replace(~r/ /, "_")])
case status do
0 -> out |> String.trim()
_ -> ""
end
end
def html(content, filename) do
lexer = lexer(filename)
cmd = "./size #{byte_size(content)} pygmentize -l #{lexer} -f html"
IO.inspect(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}")
content
{^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 ->
html_port(content, port, acc)
end
end
end