Skip to content

Commit

Permalink
Fallback to the default error format when a file is empty
Browse files Browse the repository at this point in the history
This change resolves a bad match error that occurs when a .erl file is
empty by falling back to the default error format.
  • Loading branch information
williamthome committed Dec 18, 2024
1 parent 1959c16 commit ff987ad
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
16 changes: 9 additions & 7 deletions apps/rebar/src/rebar_compiler_format.erl
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ format(Source, {Line, Column}, Extra, Desc, Config) ->
end.

find_line(Nth, Source) ->
try
{ok, Bin} = file:read_file(Source),
Splits = re:split(Bin, "(?:\n|\r\n|\r)", [{newline, anycrlf}]),
{ok, lists:nth(Nth, Splits)}
catch
error:X -> {error, X}
end.
case file:read_file(Source) of
{ok, <<>>} ->
{error, empty_file};
{ok, Bin} ->
Splits = re:split(Bin, "(?:\n|\r\n|\r)", [{newline, anycrlf}]),
{ok, lists:nth(Nth, Splits)};
{error, Reason} ->
{error, Reason}
end.

indent(0, _) -> "";
indent(N, <<"\t", Rest/binary>>) -> [$\t | indent(N-1, Rest)];
Expand Down
8 changes: 7 additions & 1 deletion apps/rebar/test/rebar_compiler_format_SUITE.erl
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ init_per_testcase(_, Config) ->
application:set_env(cf, colour_term, cf_term:has_color("dumb")),
FileName = filename:join(?config(priv_dir, Config), "oracle.erl"),
ok = file:write_file(FileName, oracle()),
EmptyFileName = filename:join(?config(priv_dir, Config), "empty.erl"),
ok = file:write_file(EmptyFileName, ""),
Conf = dict:from_list([{compiler_error_format, rich}]),
[{conf, Conf}, {file, FileName}, {term, OriginalTerm} | Config].
[{conf, Conf}, {file, FileName}, {empty_file, EmptyFileName}, {term, OriginalTerm} | Config].

end_per_testcase(_, Config) ->
case ?config(term, Config) of
Expand Down Expand Up @@ -65,6 +67,7 @@ nocolor() ->
[{doc, "testing all sorts of planned output"}].
nocolor(Config) ->
Path = ?config(file, Config),
EmptyPath = ?config(empty_file, Config),
Conf = ?config(conf, Config),
?assertEqual(" ┌─ "++Path++":"++?EOL++
""++?EOL++
Expand All @@ -90,5 +93,8 @@ nocolor(Config) ->
rebar_compiler_format:format(Path, {855,1}, "", "invalid ranges.", Conf)),
?assertEqual("/very/fake/path.oof:1:1: unknown file."++?EOL,
rebar_compiler_format:format("/very/fake/path.oof", {1,1}, "", "unknown file.", Conf)),
%% empty file
?assertEqual(EmptyPath++":1:1: should fallback to the minimal output"++?EOL,
rebar_compiler_format:format(EmptyPath, {1,1}, "", "should fallback to the minimal output", Conf)),
ok.

0 comments on commit ff987ad

Please sign in to comment.