summaryrefslogtreecommitdiff
path: root/lib/mix/test/mix/release_test.exs
blob: 56ed718e0691dcaa13d5a1dc4393a14db63bea9a (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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
Code.require_file("../test_helper.exs", __DIR__)

defmodule Mix.ReleaseTest do
  use MixTest.Case

  import Mix.Release
  doctest Mix.Release

  _ = Application.ensure_started(:eex)
  _ = Application.ensure_started(:runtime_tools)

  @erts_version :erlang.system_info(:version)
  @erts_source Path.join(:code.root_dir(), "erts-#{@erts_version}")
  @elixir_version Application.spec(:elixir, :vsn)
  @kernel_version Application.spec(:kernel, :vsn)
  @runtime_tools_version Application.spec(:runtime_tools, :vsn)
  @eex_ebin Application.app_dir(:eex, "ebin")

  setup do
    File.rm_rf!(tmp_path("mix_release"))
    File.mkdir_p!(tmp_path("mix_release"))
    :ok
  end

  describe "from_config!/3" do
    test "uses default configuration if no release is specified" do
      assert %Mix.Release{
               name: :mix,
               version: "0.1.0",
               path: path,
               version_path: version_path
             } = from_config!(nil, config(), [])

      assert String.ends_with?(path, "mix_release/_build/dev/rel/mix")
      assert String.ends_with?(version_path, "mix_release/_build/dev/rel/mix/releases/0.1.0")
    end

    test "provides default options" do
      release = from_config!(nil, config(), [])
      assert release.options == [overwrite: false, quiet: false, strip_beams: true]
    end

    test "allows overrides" do
      overrides = [path: "demo", version: "0.2.0", overwrite: true, quiet: true]
      release = from_config!(nil, config(), overrides)

      assert release.path == Path.absname("demo")
      assert release.version == "0.2.0"
      assert release.options[:overwrite]
      assert release.options[:quiet]
    end

    test "allows specifying the version from an application" do
      overrides = [version: {:from_app, :elixir}]
      release = from_config!(nil, config(), overrides)

      assert release.version == to_string(Application.spec(:elixir, :vsn))
    end

    test "raises when :from_app is used with an app that doesn't exist" do
      overrides = [version: {:from_app, :not_valid}]

      assert_raise Mix.Error,
                   ~r"Could not find version for :not_valid, please make sure the application exists",
                   fn -> from_config!(nil, config(), overrides) end
    end

    test "includes applications" do
      release = from_config!(nil, config(), [])
      assert release.applications.mix[:path] == to_charlist(Application.app_dir(:mix))
      refute release.applications.mix[:otp_app?]

      assert release.applications.kernel[:path] == to_charlist(Application.app_dir(:kernel))
      assert release.applications.kernel[:otp_app?]
    end

    test "allows release to be given as an anonymous function" do
      release = from_config!(:foo, config(releases: [foo: fn -> [version: "0.2.0"] end]), [])
      assert release.name == :foo
      assert release.version == "0.2.0"
    end

    test "uses chosen release via the CLI" do
      release =
        from_config!(
          :bar,
          config(releases: [foo: [version: "0.2.0"], bar: [version: "0.3.0"]]),
          []
        )

      assert release.name == :bar
      assert release.version == "0.3.0"
      assert String.ends_with?(release.path, "mix_release/_build/dev/rel/bar")

      assert String.ends_with?(
               release.version_path,
               "mix_release/_build/dev/rel/bar/releases/0.3.0"
             )
    end

    test "uses chosen release via the default_release" do
      release =
        from_config!(
          nil,
          config(
            default_release: :bar,
            releases: [foo: [version: "0.2.0"], bar: [version: "0.3.0"]]
          ),
          []
        )

      assert release.name == :bar
      assert release.version == "0.3.0"
      assert String.ends_with?(release.path, "mix_release/_build/dev/rel/bar")

      assert String.ends_with?(
               release.version_path,
               "mix_release/_build/dev/rel/bar/releases/0.3.0"
             )
    end

    test "raises for multiple releases and no name" do
      assert_raise Mix.Error,
                   ~r"\"mix release\" was invoked without a name but there are multiple releases",
                   fn -> from_config!(nil, config(releases: [foo: [], bar: []]), []) end
    end

    test "raises for unknown release" do
      assert_raise Mix.Error, "Unknown release :foo. The available releases are: []", fn ->
        from_config!(:foo, config(), [])
      end
    end

    test "uses the locked version of an app", context do
      in_tmp(context.test, fn ->
        # install newer version of the app in the custom ERTS
        custom_erts_path = Path.join([File.cwd!(), "erts-#{@erts_version}"])
        File.cp_r!(@erts_source, custom_erts_path)

        ebin_dir = Path.expand(Path.join([custom_erts_path, "..", "lib", "cowboy-2.0.0", "ebin"]))
        File.mkdir_p!(ebin_dir)
        app_resource = "{application,cowboy,[{vsn,\"2.0.0\"},{modules,[]},{applications,[]}]}."
        File.write!(Path.join(ebin_dir, "cowboy.app"), app_resource)

        # install older version of the app in the project dependencies
        project_path = Path.join(File.cwd!(), "project")
        build_path = Path.join(project_path, "_build")
        ebin_dir = Path.join([build_path, "dev", "lib", "cowboy", "ebin"])
        File.mkdir_p!(ebin_dir)
        app_resource = "{application,cowboy,[{vsn,\"1.1.2\"},{modules,[]},{applications,[]}]}."
        File.write!(Path.join(ebin_dir, "cowboy.app"), app_resource)

        File.mkdir_p!(Path.join([project_path, "deps", "cowboy"]))
        lockfile = Path.join(project_path, "mix.lock")

        File.write!(lockfile, ~S"""
        %{
          "cowboy": {:hex, :cowboy, "1.1.2"},
        }
        """)

        app_config =
          config(
            deps: [{:cowboy, "~> 1.0", path: "deps/cowvoy"}],
            releases: [demo: [include_erts: custom_erts_path, applications: [cowboy: :permanent]]]
          )

        Mix.Project.in_project(:mix, project_path, app_config, fn _ ->
          Code.prepend_path(ebin_dir)
          release = from_config!(nil, app_config, [])
          assert release.applications.cowboy[:vsn] == ~c"1.1.2"
        end)
      end)
    end

    test "uses the latest version of an app if it is not locked", context do
      in_tmp(context.test, fn ->
        test_erts_dir = Path.join(File.cwd!(), "erts-#{@erts_version}")
        test_libs_dir = Path.join(File.cwd!(), "lib")
        libs_dir = Path.join(:code.root_dir(), "lib")
        libs = File.ls!(libs_dir)

        File.cp_r!(@erts_source, test_erts_dir)

        for lib <- libs,
            source_file <- Path.wildcard(Path.join([libs_dir, lib, "ebin", "*.app"])) do
          target_dir = Path.join([test_libs_dir, lib, "ebin"])
          target_file = Path.join(target_dir, Path.basename(source_file))

          File.mkdir_p!(target_dir)
          File.cp!(source_file, target_file)
        end

        File.mkdir_p!(Path.join("lib", "compiler-1.0"))

        release = from_config!(nil, config(releases: [demo: [include_erts: test_erts_dir]]), [])

        assert Path.dirname(release.applications.compiler[:path]) == test_libs_dir
        assert release.applications.compiler[:vsn] != "1.0"
      end)
    end

    test "raises on unknown app" do
      assert_raise Mix.Error, "Could not find application :unknown", fn ->
        from_config!(nil, config(releases: [demo: [applications: [unknown: :none]]]), [])
      end
    end

    test "raises for missing version" do
      assert_raise Mix.Error, ~r"No :version found", fn ->
        from_config!(nil, config() |> Keyword.drop([:version]), [])
      end
    end

    test "raises for blank version" do
      assert_raise Mix.Error, ~r"The release :version cannot be an empty string", fn ->
        from_config!(nil, config(version: ""), [])
      end
    end

    test "raises on invalid release names" do
      assert_raise Mix.Error, ~r"Invalid release name", fn ->
        from_config!(nil, config(releases: ["invalid name": []]), [])
      end
    end

    test "raises on bad steps" do
      assert_raise Mix.Error,
                   ~r"The :steps option must be",
                   fn -> release(steps: :foo) end

      assert_raise Mix.Error,
                   ~r"The :steps option must contain the atom :assemble once, got: \[\]",
                   fn -> release(steps: []) end

      assert_raise Mix.Error,
                   ~r"The :steps option must contain the atom :assemble once",
                   fn -> release(steps: [:assemble, :assemble]) end

      assert_raise Mix.Error,
                   ~r"The :tar step must come after :assemble",
                   fn -> release(steps: [:tar, :assemble]) end

      assert_raise Mix.Error,
                   ~r"The :steps option can only contain the atom :tar once",
                   fn -> release(steps: [:assemble, :tar, :tar]) end

      assert_raise Mix.Error,
                   ~r"The :steps option must be",
                   fn -> release(steps: [:foo]) end
    end
  end

  describe "from_config!/3 + umbrella" do
    test "cannot infer for umbrella projects" do
      assert_raise Mix.Error,
                   ~r"Umbrella projects require releases to be explicitly defined",
                   fn -> from_config!(nil, config(apps_path: "apps"), []) end
    end

    test "requires apps for umbrella projects" do
      assert_raise Mix.Error,
                   ~r"Umbrella projects require releases to be explicitly defined",
                   fn -> from_config!(nil, config(apps_path: "apps", releases: [foo: []]), []) end
    end

    test "builds explicit releases with applications" do
      config = config(apps_path: "apps", releases: [foo: [applications: [mix: :permanent]]])

      assert %Mix.Release{
               name: :foo,
               version: "0.1.0",
               path: _path,
               version_path: _version_path
             } = from_config!(nil, config, [])
    end
  end

  describe "from_config!/3 + boot_scripts" do
    test "generates a start boot script with current application" do
      release = release([])

      assert release.boot_scripts.start == [
               kernel: :permanent,
               stdlib: :permanent,
               elixir: :permanent,
               sasl: :permanent,
               mix: :permanent,
               iex: :none,
               compiler: :permanent
             ]
    end

    test "includes extra application in order" do
      # Current app is always last
      release = release(applications: [eex: :permanent])

      assert release.boot_scripts.start == [
               kernel: :permanent,
               stdlib: :permanent,
               elixir: :permanent,
               sasl: :permanent,
               eex: :permanent,
               mix: :permanent,
               iex: :none,
               compiler: :permanent
             ]

      # Unless explicitly given
      release = release(applications: [mix: :permanent, eex: :permanent])

      assert release.boot_scripts.start == [
               kernel: :permanent,
               stdlib: :permanent,
               elixir: :permanent,
               sasl: :permanent,
               mix: :permanent,
               eex: :permanent,
               iex: :none,
               compiler: :permanent
             ]
    end

    test "configures other applications" do
      release = release(applications: [mix: :temporary])
      assert release.boot_scripts.start[:mix] == :temporary

      release = release(applications: [iex: :temporary])
      assert release.boot_scripts.start[:iex] == :temporary
    end

    test "configures other applications in cascade", context do
      in_tmp(context.test, fn ->
        app =
          {:application, :my_sample_mode,
           applications: [:kernel, :stdlib, :elixir, :runtime_tools, :compiler],
           description: ~c"my_sample_mode",
           modules: [],
           vsn: ~c"1.0.0"}

        File.mkdir_p!("my_sample_mode/ebin")
        Code.prepend_path("my_sample_mode/ebin")
        format = :io_lib.format("%% coding: utf-8~n~p.~n", [app])
        File.write!("my_sample_mode/ebin/my_sample_mode.app", format)

        apps = [my_sample_mode: :temporary]
        release = release(applications: apps)
        assert release.boot_scripts.start[:my_sample_mode] == :temporary
        assert release.boot_scripts.start[:runtime_tools] == :temporary
        assert release.boot_scripts.start[:compiler] == :permanent

        apps = [my_sample_mode: :temporary, elixir: :permanent]
        release = release(applications: apps)
        assert release.boot_scripts.start[:my_sample_mode] == :temporary
        assert release.boot_scripts.start[:runtime_tools] == :temporary
        assert release.boot_scripts.start[:compiler] == :permanent

        apps = [my_sample_mode: :temporary, runtime_tools: :none, compiler: :none]
        release = release(applications: apps)
        assert release.boot_scripts.start[:my_sample_mode] == :temporary
        assert release.boot_scripts.start[:runtime_tools] == :none
        assert release.boot_scripts.start[:compiler] == :none

        apps = [my_sample_mode: :temporary, elixir: :permanent, compiler: :none]
        release = release(applications: apps)
        assert release.boot_scripts.start[:my_sample_mode] == :temporary
        assert release.boot_scripts.start[:runtime_tools] == :temporary
        assert release.boot_scripts.start[:compiler] == :none
      end)
    end

    test "generates a start_clean script with only kernel and stdlib starting up" do
      release = release([])

      assert release.boot_scripts.start_clean == [
               kernel: :permanent,
               stdlib: :permanent,
               elixir: :none,
               sasl: :none,
               mix: :none,
               iex: :none,
               compiler: :none
             ]
    end
  end

  describe "from_config!/3 + include_erts" do
    test "when true (default)" do
      release = release([])
      assert release.erts_version == @erts_version
      assert release.erts_source == to_charlist(@erts_source)
    end

    test "when false" do
      release = release(include_erts: false)
      assert release.erts_version == @erts_version
      assert release.erts_source == nil
    end

    test "when anonymous function" do
      release = release(include_erts: fn -> true end)
      assert release.erts_version == @erts_version
      assert release.erts_source == to_charlist(@erts_source)

      release = release(include_erts: fn -> false end)
      assert release.erts_version == @erts_version
      assert release.erts_source == nil
    end

    test "with valid path" do
      release = release(include_erts: @erts_source)
      assert release.erts_version == @erts_version
      assert release.erts_source == to_charlist(@erts_source)
    end

    test "with invalid path" do
      assert_raise Mix.Error, "Could not find ERTS system at \"bad\"", fn ->
        release(include_erts: "bad")
      end
    end
  end

  describe "make_boot_script/4" do
    @boot_script_path tmp_path("mix_release/start")

    test "writes .rel, .boot, and .script files" do
      release = release([])
      assert make_boot_script(release, @boot_script_path, release.boot_scripts.start) == :ok

      assert {:ok,
              [
                {:release, {~c"demo", ~c"0.1.0"}, {:erts, @erts_version},
                 [
                   {:kernel, _, :permanent},
                   {:stdlib, _, :permanent},
                   {:elixir, @elixir_version, :permanent},
                   {:sasl, _, :permanent},
                   {:mix, @elixir_version, :permanent},
                   {:iex, @elixir_version, :none},
                   {:compiler, _, :permanent}
                 ]}
              ]} = :file.consult(@boot_script_path <> ".rel")

      assert {:ok, [{:script, {~c"demo", ~c"0.1.0"}, instructions}]} =
               :file.consult(@boot_script_path <> ".script")

      assert {:path, [~c"$ROOT/lib/kernel-#{@kernel_version}/ebin"]} in instructions
      assert {:path, [~c"$RELEASE_LIB/elixir-#{@elixir_version}/ebin"]} in instructions

      assert File.read!(@boot_script_path <> ".boot") |> :erlang.binary_to_term() ==
               {:script, {~c"demo", ~c"0.1.0"}, instructions}
    end

    test "prepends relevant paths" do
      release = release([])

      assert make_boot_script(
               release,
               @boot_script_path,
               release.boot_scripts.start,
               ["$RELEASE_LIB/sample"]
             ) == :ok

      assert {:ok, [{:script, {~c"demo", ~c"0.1.0"}, instructions}]} =
               :file.consult(@boot_script_path <> ".script")

      assert {:path, [~c"$ROOT/lib/kernel-#{@kernel_version}/ebin"]} in instructions
      refute {:path, [~c"$RELEASE_LIB/elixir-#{@elixir_version}/ebin"]} in instructions

      assert {:path, [~c"$RELEASE_LIB/sample", ~c"$RELEASE_LIB/elixir-#{@elixir_version}/ebin"]} in instructions

      assert File.read!(@boot_script_path <> ".boot") |> :erlang.binary_to_term() ==
               {:script, {~c"demo", ~c"0.1.0"}, instructions}
    end

    test "works when :load/:none is set at the leaf" do
      release = release(applications: [mix: :none])
      assert make_boot_script(release, @boot_script_path, release.boot_scripts.start) == :ok
      {:ok, [{:release, _, _, rel_apps}]} = :file.consult(@boot_script_path <> ".rel")
      assert List.keyfind(rel_apps, :mix, 0) == {:mix, @elixir_version, :none}
    end

    test "works when :load/:none is set at the subtree" do
      release = release(applications: [mix: :load, elixir: :load, iex: :load])
      assert make_boot_script(release, @boot_script_path, release.boot_scripts.start) == :ok
      {:ok, [{:release, _, _, rel_apps}]} = :file.consult(@boot_script_path <> ".rel")
      assert {:elixir, _, :load} = List.keyfind(rel_apps, :elixir, 0)
      assert {:iex, _, :load} = List.keyfind(rel_apps, :iex, 0)
      assert {:mix, _, :load} = List.keyfind(rel_apps, :mix, 0)
    end

    test "raises on unknown app" do
      {:error, message} = make_boot_script(release([]), @boot_script_path, unknown: :permanent)
      assert message =~ "Unknown application :unknown"
    end

    test "raises on missing dependency" do
      {:error, message} = make_boot_script(release([]), @boot_script_path, elixir: :permanent)

      assert message =~
               "Application :elixir is listed in the release boot, but it depends on :kernel, which isn't"
    end

    test "raises on unknown mode" do
      {:error, message} = make_boot_script(release([]), @boot_script_path, mix: :what)
      assert message =~ "Unknown mode :what for :mix"
    end

    test "raises on bad load/none" do
      release = release(applications: [kernel: :load])
      {:error, message} = make_boot_script(release, @boot_script_path, release.boot_scripts.start)

      assert message =~
               "Application :stdlib has mode :permanent but it depends on :kernel which is set to :load"

      release = release(applications: [elixir: :none])
      {:error, message} = make_boot_script(release, @boot_script_path, release.boot_scripts.start)

      assert message =~
               "Application :mix has mode :permanent but it depends on :elixir which is set to :none"
    end

    test "does not raise on child unsafe mode if parent is in `skip_mode_validation_for`" do
      # `:mix` is a parent that depends on `:elixir`
      release = release(applications: [elixir: :load], skip_mode_validation_for: [:mix])
      assert make_boot_script(release, @boot_script_path, release.boot_scripts.start) == :ok
      assert make_boot_script(release, @boot_script_path, release.boot_scripts.start_clean) == :ok
    end
  end

  describe "make_cookie/1" do
    @cookie_path tmp_path("mix_release/cookie")

    test "creates a random cookie if no cookie" do
      assert make_cookie(release([]), @cookie_path) == :ok
      assert byte_size(File.read!(@cookie_path)) == 56
    end

    test "uses the given cookie" do
      release = release(cookie: "abcdefghijk")
      assert make_cookie(release, @cookie_path) == :ok
      assert File.read!(@cookie_path) == "abcdefghijk"
      assert make_cookie(release, @cookie_path) == :ok
    end

    test "asks to change if the cookie changes" do
      assert make_cookie(release(cookie: "abcdefghijk"), @cookie_path) == :ok

      send(self(), {:mix_shell_input, :yes?, false})
      assert make_cookie(release(cookie: "lmnopqrstuv"), @cookie_path) == :ok
      assert File.read!(@cookie_path) == "abcdefghijk"

      send(self(), {:mix_shell_input, :yes?, true})
      assert make_cookie(release(cookie: "lmnopqrstuv"), @cookie_path) == :ok
      assert File.read!(@cookie_path) == "lmnopqrstuv"
    end

    test "does not ask to change if set to overwrite" do
      assert make_cookie(release([]), @cookie_path) == :ok
      send(self(), {:mix_shell_input, :yes?, false})
      assert make_cookie(release([cookie: "lmnopqrstuv"], overwrite: true), @cookie_path) == :ok
      assert File.read!(@cookie_path) == "lmnopqrstuv"
    end
  end

  describe "make_start_erl/1" do
    @start_erl_path tmp_path("mix_release/start_erl.data")

    test "writes ERTS and release versions" do
      assert make_start_erl(release([]), @start_erl_path) == :ok
      assert File.read!(@start_erl_path) == "#{@erts_version} 0.1.0"
    end
  end

  describe "make_sys_config/1" do
    @sys_config tmp_path("mix_release/_build/dev/rel/demo/releases/0.1.0/sys.config")
    @providers [{Config.Reader, "/foo/bar/baz"}]

    test "writes the given sys_config" do
      assert make_sys_config(release([]), [foo: [bar: :baz]], "unused/runtime/path") == :ok
      contents = File.read!(@sys_config)
      assert contents =~ "%% RUNTIME_CONFIG=false"
      assert contents =~ "[{foo,[{bar,baz}]}]."
    end

    test "writes sys_config with encoding" do
      assert make_sys_config(
               release([]),
               [encoding: {:_μ, :"£", "£", ~c"£"}],
               "unused/runtime/path"
             ) ==
               :ok

      {:ok, contents} = :file.consult(@sys_config)
      assert contents == [[encoding: {:_μ, :"£", "£", ~c"£"}]]
    end

    test "writes the given sys_config with config providers" do
      release = release(config_providers: @providers, reboot_system_after_config: true)
      assert make_sys_config(release, [kernel: [key: :value]], "/foo/bar/bat") == :ok
      assert File.read!(@sys_config) =~ "%% RUNTIME_CONFIG=true"
      {:ok, [config]} = :file.consult(@sys_config)
      assert %Config.Provider{} = provider = config[:elixir][:config_provider_init]
      refute provider.prune_runtime_sys_config_after_boot
      assert provider.extra_config == [kernel: [start_distribution: true]]
      assert config[:kernel] == [key: :value, start_distribution: false]
    end

    test "writes the given sys_config without distribution and with pruning" do
      release =
        release(
          config_providers: @providers,
          reboot_system_after_config: true,
          start_distribution_during_config: true,
          prune_runtime_sys_config_after_boot: true
        )

      assert make_sys_config(release, [kernel: [key: :value]], "/foo/bar/bat") == :ok
      assert File.read!(@sys_config) =~ "%% RUNTIME_CONFIG=true"
      {:ok, [config]} = :file.consult(@sys_config)
      assert %Config.Provider{} = provider = config[:elixir][:config_provider_init]
      assert provider.reboot_system_after_config
      assert provider.prune_runtime_sys_config_after_boot
      assert provider.extra_config == []
      assert config[:kernel] == [key: :value]
    end

    test "writes the given sys_config without reboot" do
      release = release(config_providers: @providers, reboot_system_after_config: false)
      assert make_sys_config(release, [kernel: [key: :value]], "/foo/bar/bat") == :ok
      assert File.read!(@sys_config) =~ "%% RUNTIME_CONFIG=false"
      {:ok, [config]} = :file.consult(@sys_config)
      assert %Config.Provider{} = provider = config[:elixir][:config_provider_init]
      refute provider.reboot_system_after_config
      assert provider.extra_config == []
      assert config[:kernel] == [key: :value]
    end

    test "errors on bad config" do
      assert {:error, "Could not read configuration file." <> _} =
               make_sys_config(release([]), [foo: [bar: self()]], "unused/runtime/path")

      env = %{__ENV__ | lexical_tracker: self()}

      assert {:error, "Could not read configuration file." <> _} =
               make_sys_config(release([]), [foo: [bar: env]], "unused/runtime/path")
    end
  end

  describe "copy_erts/1" do
    test "copies to directory" do
      assert copy_erts(release(include_erts: true))
      destination = tmp_path("mix_release/_build/dev/rel/demo/erts-#{@erts_version}")
      assert File.exists?(destination)

      assert File.read!(Path.join(destination, "bin/erl")) =~
               ~s|ROOTDIR="${ERL_ROOTDIR:-"$(dirname "$(dirname "$BINDIR")")"}|

      unless match?({:win32, _}, :os.type()) do
        assert File.lstat!(Path.join(destination, "bin/erl")).mode |> rem(0o1000) == 0o755
      end

      refute File.exists?(Path.join(destination, "bin/erl.ini"))
      refute File.exists?(Path.join(destination, "doc"))

      # Now we copy from the copy using a string and without src
      new_destination = tmp_path("mix_release/_build/dev/rel/new_demo/erts-#{@erts_version}")
      File.rm_rf!(Path.join(destination, "src"))

      release = from_config!(nil, config(releases: [new_demo: [include_erts: destination]]), [])
      assert copy_erts(release)
      assert File.exists?(new_destination)
    end

    test "does not copy when include_erts is false" do
      refute copy_erts(release(include_erts: false))
      destination = tmp_path("mix_release/_build/dev/rel/demo/erts-#{@erts_version}")
      refute File.exists?(destination)
    end
  end

  describe "copy_ebin/3" do
    test "copies and strips beams" do
      assert copy_ebin(release([]), @eex_ebin, tmp_path("eex_ebin"))

      assert size!(Path.join(@eex_ebin, "eex.app")) ==
               size!(tmp_path("eex_ebin/eex.app"))

      assert size!(Path.join(@eex_ebin, "Elixir.EEx.beam")) >
               size!(tmp_path("eex_ebin/Elixir.EEx.beam"))
    end

    test "copies without stripping beams" do
      assert copy_ebin(release(strip_beams: false), @eex_ebin, tmp_path("eex_ebin"))

      assert size!(Path.join(@eex_ebin, "eex.app")) ==
               size!(tmp_path("eex_ebin/eex.app"))

      assert size!(Path.join(@eex_ebin, "Elixir.EEx.beam")) ==
               size!(tmp_path("eex_ebin/Elixir.EEx.beam"))
    end

    test "returns false for unknown or empty directories" do
      source = tmp_path("mix_release")
      refute copy_ebin(release([]), source, tmp_path("mix_release"))
      File.mkdir_p!(source)
      refute copy_ebin(release([]), source, tmp_path("mix_release"))
    end

    test "preserves file mode" do
      source = tmp_path("source_ebin")
      source_so_path = Path.join(source, "libtest_nif.so")

      File.mkdir_p!(source)
      File.touch!(source_so_path)
      File.chmod!(source_so_path, 0o755)

      assert copy_ebin(release([]), source, tmp_path("mix_release"))

      assert mode!(source_so_path) == mode!(tmp_path("mix_release/libtest_nif.so"))
    end
  end

  describe "copy_app/2" do
    @release_lib tmp_path("mix_release/_build/dev/rel/demo/lib")

    test "copies and strips beams" do
      assert copy_app(release(applications: [eex: :permanent]), :eex)

      assert size!(Path.join(@eex_ebin, "eex.app")) ==
               size!(Path.join(@release_lib, "eex-#{@elixir_version}/ebin/eex.app"))

      assert size!(Path.join(@eex_ebin, "Elixir.EEx.beam")) >
               size!(Path.join(@release_lib, "eex-#{@elixir_version}/ebin/Elixir.EEx.beam"))
    end

    test "copies without stripping beams" do
      assert copy_app(release(strip_beams: false, applications: [eex: :permanent]), :eex)

      assert size!(Path.join(@eex_ebin, "eex.app")) ==
               size!(Path.join(@release_lib, "eex-#{@elixir_version}/ebin/eex.app"))

      assert size!(Path.join(@eex_ebin, "Elixir.EEx.beam")) ==
               size!(Path.join(@release_lib, "eex-#{@elixir_version}/ebin/Elixir.EEx.beam"))
    end

    test "copies OTP apps" do
      release = release(applications: [runtime_tools: :permanent])
      assert copy_app(release, :runtime_tools)
      assert File.exists?(Path.join(@release_lib, "runtime_tools-#{@runtime_tools_version}/ebin"))
      assert File.exists?(Path.join(@release_lib, "runtime_tools-#{@runtime_tools_version}/priv"))
    end

    test "does not copy OTP app if include_erts is false" do
      release = release(include_erts: false, applications: [runtime_tools: :permanent])
      refute copy_app(release, :runtime_tools)
      refute File.exists?(Path.join(@release_lib, "runtime_tools-#{@runtime_tools_version}/ebin"))
      refute File.exists?(Path.join(@release_lib, "runtime_tools-#{@runtime_tools_version}/priv"))
    end
  end

  describe "strip_beam/1" do
    test "excludes at least docs and dbgi chunks" do
      {:ok, beam} =
        Path.join(@eex_ebin, "Elixir.EEx.beam")
        |> File.read!()
        |> strip_beam()

      assert {:error, :beam_lib, {:missing_chunk, _, ~c"Dbgi"}} =
               :beam_lib.chunks(beam, [~c"Dbgi"])

      assert {:error, :beam_lib, {:missing_chunk, _, ~c"Docs"}} =
               :beam_lib.chunks(beam, [~c"Docs"])
    end

    test "can keep docs and debug info, if requested" do
      {:ok, beam} =
        Path.join(@eex_ebin, "Elixir.EEx.beam")
        |> File.read!()
        |> strip_beam(keep: ["Docs", "Dbgi"])

      assert {:ok, {EEx, [{~c"Dbgi", _}]}} = :beam_lib.chunks(beam, [~c"Dbgi"])
      assert {:ok, {EEx, [{~c"Docs", _}]}} = :beam_lib.chunks(beam, [~c"Docs"])
    end

    test "strip beams without compression" do
      {:ok, beam} =
        Path.join(@eex_ebin, "Elixir.EEx.beam")
        |> File.read!()
        |> strip_beam(compress: false)

      assert match?(<<"FOR1", _::binary>>, beam)
    end
  end

  describe "included applications" do
    test "are included in the release", context do
      in_tmp(context.test, fn ->
        app =
          {:application, :my_sample1,
           applications: [:kernel, :stdlib, :elixir],
           description: ~c"my_sample1",
           modules: [],
           vsn: ~c"1.0.0",
           included_applications: [:runtime_tools]}

        File.mkdir_p!("my_sample1/ebin")
        Code.prepend_path("my_sample1/ebin")
        format = :io_lib.format("%% coding: utf-8~n~p.~n", [app])
        File.write!("my_sample1/ebin/my_sample1.app", format)

        release = release(applications: [my_sample1: :permanent])
        assert release.boot_scripts.start[:runtime_tools] == :load

        release = release(applications: [my_sample1: :permanent, runtime_tools: :none])
        assert release.boot_scripts.start[:runtime_tools] == :none
      end)
    end

    test "raise on conflict", context do
      in_tmp(context.test, fn ->
        app =
          {:application, :my_sample2,
           applications: [:kernel, :stdlib, :elixir, :runtime_tools],
           description: ~c"my_sample",
           modules: [],
           vsn: ~c"1.0.0",
           included_applications: [:runtime_tools]}

        File.mkdir_p!("my_sample2/ebin")
        Code.prepend_path("my_sample2/ebin")
        format = :io_lib.format("%% coding: utf-8~n~p.~n", [app])
        File.write!("my_sample2/ebin/my_sample2.app", format)

        assert_raise Mix.Error,
                     ":runtime_tools is listed both as a regular application and as an included application",
                     fn -> release(applications: [my_sample2: :permanent]) end
      end)
    end
  end

  describe "optional applications" do
    test "are ignored if not available", context do
      in_tmp(context.test, fn ->
        app =
          {:application, :my_sample1,
           applications: [:kernel, :stdlib, :elixir, :unknown],
           optional_applications: [:unknown],
           description: ~c"my_sample1",
           modules: [],
           vsn: ~c"1.0.0"}

        File.mkdir_p!("my_sample1/ebin")
        Code.prepend_path("my_sample1/ebin")
        format = :io_lib.format("%% coding: utf-8~n~p.~n", [app])
        File.write!("my_sample1/ebin/my_sample1.app", format)

        release = release(applications: [my_sample1: :permanent])
        assert release.boot_scripts.start[:unknown] == nil
      end)
    end
  end

  defp size!(path) do
    File.stat!(path).size
  end

  defp mode!(path) do
    File.stat!(path).mode
  end

  defp release(config, overrides \\ []) do
    from_config!(nil, config(releases: [demo: config]), overrides)
  end

  defp config(extra \\ []) do
    [
      app: :mix,
      version: "0.1.0",
      build_path: tmp_path("mix_release/_build"),
      build_per_environment: true,
      config_path: tmp_path("mix_release/config/config.exs")
    ]
    |> Keyword.merge(extra)
  end

  defmodule ReleaseApp do
    def project do
      [
        app: :mix,
        version: "0.1.0",
        build_path: tmp_path("mix_release/_build"),
        build_per_environment: true,
        config_path: tmp_path("mix_release/config/config.exs")
      ]
      |> Keyword.merge(Process.get(:project))
    end
  end
end