Current section
Files
Jump to
Current section
Files
src/rebar3_strata_compile.erl
-module(rebar3_strata_compile).
-export([init/1, do/1, format_error/1]).
-define(PROVIDER, compile).
-define(DEPS, [{default, lock}]).
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
Provider = providers:create([
{name, ?PROVIDER},
{module, ?MODULE},
{namespace, strata},
{bare, true},
{deps, ?DEPS},
{example, "rebar3 strata compile"},
{opts, []},
{short_desc, "Compile schema migrations"},
{desc, "Compile schema migrations"}
]),
{ok, rebar_state:add_provider(State, Provider)}.
do(State) ->
MigrationsPath = rebar3_strata_config:get_path(State),
Paths = list_migrations_dir(MigrationsPath),
ProcessedPaths = process_paths(Paths),
Gen = generate_schema_migrations(ProcessedPaths),
StrataMigrationsPath = filename:join(MigrationsPath, "strata_migrations.erl"),
case file:open(StrataMigrationsPath, [write]) of
{ok, F} ->
file:write(F, Gen),
file:close(F);
_ ->
throw("Unable to create strata_migrations.erl at path provided")
end,
{ok, State}.
format_error(Reason) ->
io_lib:format("~p", [Reason]).
list_migrations_dir(Path) ->
case file:list_dir(Path) of
{ok, Paths} ->
Paths;
_ ->
throw("Unable to list migrations dir with path provided")
end.
process_paths(Paths) ->
filter_schema_migrations(lists:map(fun process_path/1, Paths)).
process_path(Path) ->
Base = filename:basename(Path, filename:extension(Path)),
[_ | TimestampS] = string:split(Base, "_", trailing),
{Base, TimestampS}.
filter_schema_migrations(Paths) ->
lists:filter(fun ({Path, _}) ->
not string:equal(Path, <<"strata_migrations">>)
end, Paths).
generate_schema_migrations(ProcessedPaths) ->
[io_lib:format("-module(strata_migrations).~n", []),
io_lib:format("-export([init/0]).~n", []),
io_lib:format("init() ->~n", []),
io_lib:format(" #{~n", [])] ++
generate_schemas(ProcessedPaths) ++
[io_lib:format(" }.~n", [])].
generate_schemas(ProcessedPaths) ->
Len = length(ProcessedPaths),
generate_schemas(ProcessedPaths, Len, 0, []).
generate_schemas([], _, _, Acc) ->
lists:reverse(Acc);
generate_schemas([{<<"strata_migrations">>, _} | T], Len, Count, Acc) ->
generate_schemas(T, Len, Count + 1, Acc);
generate_schemas([{ModuleName, Timestamp} | T], Len, Count, Acc) when Count + 1 >= Len ->
Result = io_lib:format(" ~s => ~s~n", [ModuleName, Timestamp]),
generate_schemas(T, Len, Count + 1, [Result | Acc]);
generate_schemas([{ModuleName, Timestamp} | T], Len, Count, Acc) ->
Result = io_lib:format(" ~s => ~s,~n", [ModuleName, Timestamp]),
generate_schemas(T, Len, Count + 1, [Result | Acc]).