Current section
Files
Jump to
Current section
Files
src/libero@format.erl
-module(libero@format).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/libero/format.gleam").
-export([format_gleam/1]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
?MODULEDOC(
" Run `gleam format` on generated Gleam code.\n"
"\n"
" Writes code to a temp file, runs the formatter, reads back the result.\n"
" Falls back to the original string if formatting fails.\n"
).
-file("src/libero/format.gleam", 63).
-spec run_format_command(binary()) -> {integer(), binary()}.
run_format_command(Tmp) ->
case libero_cli_ffi:find_executable(<<"gleam"/utf8>>) of
none ->
{-1, <<"gleam executable not found on PATH"/utf8>>};
{some, Path} ->
libero_cli_ffi:run_executable_capturing(
Path,
[<<"format"/utf8>>, Tmp]
)
end.
-file("src/libero/format.gleam", 42).
-spec run_format(binary(), binary()) -> binary().
run_format(Tmp, Fallback) ->
{Exit_code, Output} = run_format_command(Tmp),
case Exit_code of
0 ->
_pipe = simplifile:read(Tmp),
gleam@result:unwrap(_pipe, Fallback);
_ ->
gleam_stdlib:println_error(
<<<<"warning: gleam format failed (exit code "/utf8,
(erlang:integer_to_binary(Exit_code))/binary>>/binary,
"), using unformatted output"/utf8>>
),
case gleam@string:trim(Output) of
<<""/utf8>> ->
nil;
Trimmed ->
gleam_stdlib:println_error(<<" "/utf8, Trimmed/binary>>)
end,
Fallback
end.
-file("src/libero/format.gleam", 79).
-spec get_tmp_dir() -> binary().
get_tmp_dir() ->
_pipe = libero_cli_ffi:get_env(<<"TMPDIR"/utf8>>),
_pipe@1 = gleam@option:lazy_or(
_pipe,
fun() -> libero_cli_ffi:get_env(<<"TMP"/utf8>>) end
),
_pipe@2 = gleam@option:lazy_or(
_pipe@1,
fun() -> libero_cli_ffi:get_env(<<"TEMP"/utf8>>) end
),
gleam@option:unwrap(_pipe@2, <<"/tmp"/utf8>>).
-file("src/libero/format.gleam", 18).
?DOC(
" Format a string of Gleam code using `gleam format`.\n"
" Returns the formatted code, or the original if formatting fails.\n"
" nolint: thrown_away_error -- intentional fallback: formatting is best-effort\n"
).
-spec format_gleam(binary()) -> binary().
format_gleam(Code) ->
Suffix = begin
_pipe = crypto:strong_rand_bytes(8),
gleam_stdlib:base16_encode(_pipe)
end,
Tmp_dir = get_tmp_dir(),
Tmp = <<<<<<Tmp_dir/binary, "/libero_fmt_"/utf8>>/binary, Suffix/binary>>/binary,
".gleam"/utf8>>,
case simplifile:write(Tmp, Code) of
{error, _} ->
gleam_stdlib:println_error(
<<"warning: could not write temp file for formatting, skipping gleam format"/utf8>>
),
Code;
{ok, _} ->
Formatted = run_format(Tmp, Code),
_ = simplifile_erl:delete(Tmp),
Formatted
end.