Skip to content

Commit 44405c3

Browse files
authored
Ensure no double newlines in files generated by "mix new" (#15711)
1 parent a9021b1 commit 44405c3

1 file changed

Lines changed: 15 additions & 22 deletions

File tree

lib/mix/test/mix/tasks/new_test.exs

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,8 @@ defmodule Mix.Tasks.NewTest do
1616
assert file =~ "version: \"0.1.0\""
1717
end)
1818

19-
assert_file("hello_world/README.md", fn file ->
20-
assert file =~ "# HelloWorld\n"
21-
assert String.ends_with?(file, "\n")
22-
refute String.ends_with?(file, "\n\n")
23-
end)
24-
25-
assert_file("hello_world/.gitignore", fn file ->
26-
assert String.ends_with?(file, "\n")
27-
refute String.ends_with?(file, "\n\n")
28-
end)
19+
assert_file("hello_world/README.md", ~r/# HelloWorld\n/)
20+
assert_file("hello_world/.gitignore")
2921

3022
assert_file("hello_world/lib/hello_world.ex", ~r/defmodule HelloWorld do/)
3123
assert_file("hello_world/test/test_helper.exs", ~r/ExUnit.start()/)
@@ -126,16 +118,8 @@ defmodule Mix.Tasks.NewTest do
126118
assert file =~ "apps_path: \"apps\""
127119
end)
128120

129-
assert_file("hello_world/README.md", fn file ->
130-
assert file =~ "# HelloWorld\n"
131-
assert String.ends_with?(file, "\n")
132-
refute String.ends_with?(file, "\n\n")
133-
end)
134-
135-
assert_file("hello_world/.gitignore", fn file ->
136-
assert String.ends_with?(file, "\n")
137-
refute String.ends_with?(file, "\n\n")
138-
end)
121+
assert_file("hello_world/README.md", ~r/# HelloWorld\n/)
122+
assert_file("hello_world/.gitignore")
139123

140124
assert_received {:mix_shell, :info, ["* creating mix.exs"]}
141125

@@ -260,6 +244,15 @@ defmodule Mix.Tasks.NewTest do
260244

261245
defp assert_file(file) do
262246
assert File.regular?(file), "Expected #{file} to exist, but does not"
247+
content = File.read!(file)
248+
249+
# \S\n\z matches non-whitespace followed by a single newline at EOF
250+
assert content == "" or content =~ ~r/\S\n\z/,
251+
"Expected #{file} to end with a single trailing newline"
252+
253+
refute content =~ "\n\n\n", "Expected #{file} to not contain consecutive blank lines"
254+
255+
content
263256
end
264257

265258
defp assert_file(file, match) do
@@ -268,8 +261,8 @@ defmodule Mix.Tasks.NewTest do
268261
assert_file(file, &assert(&1 =~ match))
269262

270263
is_function(match, 1) ->
271-
assert_file(file)
272-
match.(File.read!(file))
264+
content = assert_file(file)
265+
match.(content)
273266
end
274267
end
275268
end

0 commit comments

Comments
 (0)