Current section

Files

Jump to
Raw

mix.exs

defmodule WebView.MixProject do
  use Mix.Project

  def project do
    [
      app: :webview_elixir,
      version: "0.1.1",
      elixir: "~> 1.20",
      start_permanent: Mix.env() == :prod,
      package: package(),
      description: description(),
      compilers: [:c_source] ++ Mix.Task.Compiler.compilers()
    ]
  end

  defp description() do
    "A webview module for Elixir"
  end

  defp package() do
    [
      licenses: ["Apache-2.0", "MIT"],
      links: %{"GitHub" => "https://github.com/rdci/webview_elixir"},
      files: ~w(c_src lib priv LICENSE.txt Makefile Makefile.linux compile.bat mix.exs README.md test)
    ]
  end
end

defmodule Mix.Tasks.Compile.CSource do
  use Mix.Task.Compiler

  def run(args) do
    if priv_empty() || nif_source_mtime_greater_than_object() || "--force" in args do
      {_, system} = :os.type()

      {cmd, cmd_args} =
        case system do
          :darwin -> {"make", []}
          :nt -> {"compile.bat", ["build"]}
          :linux -> {"make", ["-f", "Makefile.linux"]}
        end

      erl_root = :code.root_dir()
      root_dir = Path.join([erl_root, "usr", "include"])

      output =
        if "--verbose" in args do
          IO.stream()
        else
          ""
        end

      {_, ret} = System.cmd(cmd, cmd_args, env: [{"ROOT_DIR", root_dir}], into: output)

      copy_dlls_to_priv("priv")

      case ret do
        0 -> :ok
        _ -> :err
      end
    else
      :noop
    end
  end

  def clean() do
    {_, system} = :os.type()

    cond do
      system in [:darwin, :linux] -> System.cmd("make", ["clean"])
      system in [:nt] -> System.cmd("compile.bat", ["clean"])
    end
  end

  defp priv_empty() do
    File.ls!("priv") |> Enum.filter(fn n -> !String.starts_with?(n, ".") end) == []
  end

  defp nif_source_mtime_greater_than_object() do
    File.ls!("priv")
    |> Enum.map(fn n -> File.stat!(Path.join(["priv", n]), time: :posix).mtime end)
    |> Enum.sort()
    |> Enum.reverse()
    |> hd < File.stat!(Path.join(["c_src", "webview_nif.c"]), time: :posix).mtime
  end

  defp copy_dlls_to_priv(source) do
    dest = Path.join([Mix.Project.app_path(), "priv"])

    case :os.type() do
      {_, :nt} -> File.cp_r!(source, dest)
      _ -> nil
    end
  end
end