src/rally@format.erl

-module(rally@format).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/rally/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"
    " 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/rally/format.gleam", 30).
-spec run_format(binary(), binary()) -> binary().
run_format(Tmp, Fallback) ->
    case rally_cli_ffi:find_executable(<<"gleam"/utf8>>) of
        none ->
            gleam_stdlib:println_error(
                <<"warning: gleam not found on PATH, skipping format"/utf8>>
            ),
            Fallback;

        {some, Path} ->
            Exit_code = rally_cli_ffi:run_executable(
                Path,
                [<<"format"/utf8>>, 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>>
                    ),
                    Fallback
            end
    end.

-file("src/rally/format.gleam", 65).
-spec get_tmp_dir() -> binary().
get_tmp_dir() ->
    Dir = <<"./tmp/rally_format"/utf8>>,
    _ = simplifile:create_directory_all(Dir),
    Dir.

-file("src/rally/format.gleam", 11).
-spec format_gleam(binary()) -> binary().
format_gleam(Code) ->
    Suffix = rally_cli_ffi:unique_id(),
    Tmp_dir = get_tmp_dir(),
    Tmp = <<<<<<Tmp_dir/binary, "/rally_fmt_"/utf8>>/binary, Suffix/binary>>/binary,
        ".gleam"/utf8>>,
    case simplifile:write(Tmp, Code) of
        {ok, _} ->
            Formatted = run_format(Tmp, Code),
            _ = simplifile_erl:delete(Tmp),
            Formatted;

        _ ->
            gleam_stdlib:println_error(
                <<"warning: could not write temp file for formatting, skipping gleam format"/utf8>>
            ),
            Code
    end.