src/glipt@cmd@script.erl

-module(glipt@cmd@script).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/glipt/cmd/script.gleam").
-export([execute/1]).

-file("src/glipt/cmd/script.gleam", 9).
-spec execute(list(binary())) -> nil.
execute(Args) ->
    File_path = case Args of
        [F] ->
            F;

        _ ->
            <<"script.gleam"/utf8>>
    end,
    case simplifile:read(<<"gleam.toml"/utf8>>) of
        {error, _} ->
            gleam_stdlib:println_error(
                <<"Error: no gleam.toml found in current directory. Run from a Gleam project root."/utf8>>
            );

        {ok, Toml_content} ->
            Deps = glipt@internal@toml:parse_deps(Toml_content),
            Gleam_constraint = glipt@internal@toml:parse_gleam_version(
                Toml_content
            ),
            Meta = {script_meta, Gleam_constraint, [], Deps},
            Existing_source = begin
                _pipe = simplifile:read(File_path),
                gleam@result:unwrap(_pipe, <<""/utf8>>)
            end,
            New_content = glipt@internal@script:reassemble(
                Meta,
                Existing_source
            ),
            case simplifile:write(File_path, New_content) of
                {ok, nil} ->
                    gleam_stdlib:println(
                        <<"Written directives to "/utf8, File_path/binary>>
                    );

                {error, E} ->
                    gleam_stdlib:println_error(
                        <<"Error writing file: "/utf8,
                            (gleam@string:inspect(E))/binary>>
                    )
            end
    end.