summaryrefslogtreecommitdiff
path: root/lib/mix/test/mix/tasks/compile_test.exs
blob: 2b1172640885f7a37a2819606cc04f5324714f57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
Code.require_file("../../test_helper.exs", __DIR__)

defmodule Mix.Tasks.CompileTest do
  use MixTest.Case

  defmacro position(line, column), do: {line, column}

  defmodule CustomCompilers do
    def project do
      [compilers: [:elixir, :app, :custom]]
    end
  end

  defmodule DepsApp do
    def project do
      [app: :deps_app, version: "0.1.0", deps: [{:ok, "0.1.0", path: "deps/ok"}]]
    end
  end

  defmodule WrongPath do
    def project do
      [app: :apps_path_bug, apps_path: "this_path_does_not_exist"]
    end
  end

  setup do
    Mix.Project.push(MixTest.Case.Sample)
    :ok
  end

  test "compiles --list with mixfile" do
    Mix.Task.run("compile", ["--list"])

    msg = "\nEnabled compilers: yecc, leex, erlang, elixir, app, protocols"
    assert_received {:mix_shell, :info, [^msg]}

    assert_received {:mix_shell, :info, ["mix compile.elixir    # " <> _]}
  end

  test "compiles --list with custom mixfile" do
    Mix.Project.pop()
    Mix.Project.push(CustomCompilers)
    Mix.Task.run("compile", ["--list"])
    assert_received {:mix_shell, :info, ["\nEnabled compilers: elixir, app, custom, protocols"]}
  end

  test "compiles does not require all compilers available on manifest" do
    Mix.Project.pop()
    Mix.Project.push(CustomCompilers)
    assert Mix.Tasks.Compile.manifests() |> Enum.map(&Path.basename/1) == ["compile.elixir"]
  end

  test "compiles a project with mixfile" do
    in_fixture("no_mixfile", fn ->
      assert Mix.Task.run("compile", ["--verbose"]) == {:ok, []}
      assert File.regular?("_build/dev/lib/sample/ebin/Elixir.A.beam")
      assert File.regular?("_build/dev/lib/sample/ebin/sample.app")
      assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]}
      assert_received {:mix_shell, :info, ["Generated sample app"]}
      assert File.regular?("_build/dev/lib/sample/consolidated/Elixir.Enumerable.beam")

      # Noop
      Mix.Task.clear()
      assert Mix.Task.run("compile", ["--verbose"]) == {:noop, []}
      refute_received {:mix_shell, :info, ["Compiled lib/a.ex"]}

      # Consolidates protocols if manifest is out of date
      File.rm("_build/dev/lib/sample/.mix/compile.protocols")
      Mix.Task.clear()
      assert Mix.Task.run("compile", ["--verbose"]) == {:ok, []}
      refute_received {:mix_shell, :info, ["Compiled lib/a.ex"]}
      assert File.regular?("_build/dev/lib/sample/consolidated/Elixir.Enumerable.beam")

      # Purge so consolidated is picked up
      purge([Enumerable])
      assert Mix.Tasks.App.Start.run(["--verbose"]) == :ok
      assert Protocol.consolidated?(Enumerable)
    end)
  end

  test "compiles a project with cached deps information" do
    Mix.Project.pop()

    in_fixture("deps_status", fn ->
      Mix.Project.push(DepsApp)

      File.mkdir_p!("lib")

      File.write!("lib/a.ex", """
      root = File.cwd!()
      File.cd!("lib", fn ->
        %{ok: path} = Mix.Project.deps_paths()

        if Path.relative_to(path, root) != "deps/ok" do
          raise "non cached path"
        end
      end)
      """)

      assert Mix.Task.run("compile", ["--force", "--from-mix-deps-compile"]) == {:ok, []}
    end)
  end

  test "recompiles app cache if manifest changes" do
    in_fixture("no_mixfile", fn ->
      Mix.Tasks.Compile.run(["--force"])
      purge([A, B])

      File.rm!("_build/dev/lib/sample/.mix/compile.app_cache")
      Mix.Task.clear()

      Mix.Tasks.Compile.run(["--force"])
      assert File.exists?("_build/dev/lib/sample/.mix/compile.app_cache")
    end)
  end

  # A.info/0 is loaded dynamically
  @compile {:no_warn_undefined, {A, :info, 0}}

  test "adds Logger application metadata" do
    import ExUnit.CaptureLog

    in_fixture("no_mixfile", fn ->
      Process.put({MixTest.Case.Sample, :application}, extra_applications: [:logger])

      File.write!("lib/a.ex", """
      defmodule A do
      require Logger
      def info, do: Logger.info("hello")
      end
      """)

      assert Mix.Task.run("compile", []) == {:ok, []}

      try do
        assert capture_log([metadata: [:application]], &A.info/0) =~ "application=sample"
      after
        purge([A])
      end
    end)
  end

  test "returns errors from compilers when --return-errors is set" do
    in_fixture("no_mixfile", fn ->
      File.write!("lib/a.ex", """
      defmodule A do
        def my_fn(), do: $$$
      end
      """)

      file = Path.absname("lib/a.ex")

      ExUnit.CaptureIO.capture_io(:stderr, fn ->
        assert {:error, [diagnostic]} = Mix.Task.run("compile", ["--return-errors"])

        assert %Mix.Task.Compiler.Diagnostic{
                 file: ^file,
                 severity: :error,
                 position: {2, 20},
                 message: "** (SyntaxError) lib/a.ex:2:" <> _,
                 compiler_name: "Elixir"
               } = diagnostic
      end)
    end)
  end

  test "calling raise inside a macro returns a diagnostic with a position" do
    in_fixture("no_mixfile", fn ->
      File.write!("lib/a.ex", """
      defmodule A do
        defmacro custom_macro do
          raise "error"
        end
      end
      """)

      File.write!("lib/b.ex", """
      defmodule B do
        require A
        A.custom_macro()
      end
      """)

      file = Path.absname("lib/b.ex")

      ExUnit.CaptureIO.capture_io(:stderr, fn ->
        assert {:error, [diagnostic]} = Mix.Task.run("compile", ["--return-errors"])

        assert %Mix.Task.Compiler.Diagnostic{
                 file: ^file,
                 severity: :error,
                 position: 3,
                 message: "** (RuntimeError) error\n    expanding macro: A.custom_macro/0" <> _,
                 compiler_name: "Elixir"
               } = diagnostic
      end)
    end)
  end

  test "returns syntax error from an Erlang file when --return-errors is set" do
    in_fixture("no_mixfile", fn ->
      import ExUnit.CaptureIO

      file = Path.absname("src/a.erl")
      File.mkdir!("src")

      File.write!(file, """
      -module(b).
      def b(), do: b
      """)

      assert File.regular?(file)

      capture_io(fn ->
        assert {:error, [diagnostic]} = Mix.Task.run("compile", ["--force", "--return-errors"])

        assert %Mix.Task.Compiler.Diagnostic{
                 compiler_name: "erl_parse",
                 file: ^file,
                 message: "syntax error before: b",
                 position: position(2, 5),
                 severity: :error
               } = diagnostic
      end)

      refute File.regular?("ebin/Elixir.A.beam")
      refute File.regular?("ebin/Elixir.B.beam")
    end)
  end

  test "skip protocol consolidation when --no-protocol-consolidation" do
    in_fixture("no_mixfile", fn ->
      File.rm("_build/dev/lib/sample/.mix/compile.protocols")
      assert Mix.Task.run("compile", ["--no-protocol-consolidation"]) == {:ok, []}
      assert File.regular?("_build/dev/lib/sample/ebin/Elixir.A.beam")
      refute File.regular?("_build/dev/lib/sample/consolidated/Elixir.Enumerable.beam")
    end)
  end

  test "loads consolidated protocols even on --no-compile" do
    in_fixture("no_mixfile", fn ->
      File.rm("_build/dev/lib/sample/.mix/compile.protocols")
      consolidated = "_build/dev/lib/sample/consolidated" |> Path.expand() |> to_charlist()

      assert Mix.Task.run("compile") == {:ok, []}
      assert File.regular?("_build/dev/lib/sample/consolidated/Elixir.Enumerable.beam")
      assert consolidated in :code.get_path()

      Code.delete_path("_build/dev/lib/sample/consolidated")
      assert Mix.Task.rerun("compile", ["--no-compile"]) == {:noop, []}
      assert consolidated in :code.get_path()
    end)
  end

  test "loads Mix config with --erl-config" do
    in_fixture("no_mixfile", fn ->
      File.write!("mix.config", "{erl_config_app, [{value, true}]}.")
      assert Mix.Task.run("compile", ["--erl-config", "mix.config"]) == {:ok, []}
      assert File.regular?("_build/dev/lib/sample/ebin/Elixir.A.beam")
      assert Application.get_env(:erl_config_app, :value)
    end)
  after
    Application.delete_env(:erl_config_app, :value)
  end

  test "runs after_compiler callback once" do
    in_fixture("no_mixfile", fn ->
      callback = fn result -> send(self(), result) end

      assert Mix.Task.Compiler.after_compiler(:elixir, callback) == :ok
      assert Mix.Task.rerun("compile", []) == {:ok, []}
      assert_received {:ok, []}

      Mix.Task.clear()
      assert Mix.Task.rerun("compile", []) == {:noop, []}
      refute_received {:noop, []}

      Mix.Task.clear()
      assert Mix.Task.Compiler.after_compiler(:elixir, callback) == :ok
      assert Mix.Task.run("compile", []) == {:noop, []}
      assert_received {:noop, []}
    end)
  end

  test "does not crash on a project with bad path" do
    Mix.Project.pop()
    Mix.Project.push(WrongPath)

    ExUnit.CaptureIO.capture_io(fn ->
      assert Mix.Task.run("compile", ["--no-protocol-consolidation"]) == {:noop, []}
    end)
  end

  test "validates compile_env" do
    in_fixture("no_mixfile", fn ->
      File.mkdir_p!("config")

      File.write!("config/config.exs", """
      import Config
      config :sample, :hello, System.get_env("MIX_SAMPLE_HELLO")
      """)

      File.write!("lib/a.ex", """
      defmodule A do
        require Application
        _ = Application.compile_env(:sample, :hello)
      end
      """)

      System.put_env("MIX_SAMPLE_HELLO", "compile")
      Mix.Tasks.Loadconfig.run([])
      assert Mix.Tasks.Compile.All.run([]) == {:ok, []}

      System.put_env("MIX_SAMPLE_HELLO", "runtime")
      Mix.Tasks.Loadconfig.run([])
      Application.unload(:sample)

      assert_raise Mix.Error,
                   ~r/the application :sample has a different value set for key :hello during runtime compared to compile time/,
                   fn -> Mix.Tasks.Compile.All.run([]) end

      # Can start if compile env matches
      System.put_env("MIX_SAMPLE_HELLO", "compile")
      Mix.Tasks.Loadconfig.run([])
      assert Mix.Tasks.App.Start.run([]) == :ok
    end)
  after
    System.delete_env("MIX_SAMPLE_HELLO")
    Application.delete_env(:sample, :hello, persistent: true)
  end
end